I have created graph using Node and Edge class.
When I call traverseBFS method from start = 0. then It just stuck. cannot proceed further. When I use similar approach with HashMap<Integer,ArrayList<Integer>> this algorithm runs properly. Please help me how to fix this.
Complete Code
import java.util.*;
import java.io.*;
public class Dijkstra {
static class Node {
public int id;
public long dist;
public int par;
public Node(int a, long d, int b) {
id = a;
dist = d;
par = b;
}
}
static class Edge {
int to;
int weight;
public Edge(int a, int b) {
to = a;
weight = b;
}
}
static int vert;
static ArrayList<LinkedList<Edge>> list;
static int[] parent;
static long[] distance;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
vert = sc.nextInt();
int edges = sc.nextInt();
list = new ArrayList<>();
parent = new int[vert + 1];
distance = new long[vert + 1];
for (int i = 0; i <= vert; i++) {
list.add(i, new LinkedList<Edge>());
}
for (int i = 0; i < edges; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
int w = sc.nextInt();
list.get(u).add(new Edge(v, w));
list.get(v).add(new Edge(u, w));
}
traverseBFS(0);
}
public static void traverseBFS(int start) {
System.out.print("\nBFS >> \n");
boolean visited[] = new boolean[vert];
LinkedList<Integer> q = new LinkedList<>();
q.add(start);
visited[start] = true;
while (!q.isEmpty()) {
int s = q.poll();
System.out.print(s + " ");
LinkedList<Edge> temp = list.get(s);
for (Edge var : temp) {
if (!visited[var.to]) {
visited[var.to] = true;
q.add(var.to);
}
}
}
}
}
Input
5 6
1 2 2
2 5 5
2 3 4
1 4 1
4 3 3
3 5 1
Output
BFS >>
0
When posting mre consider hard coding test data, to make it easier to run a test:
public static void main(String[] args) {
int[][] neighbours = {
{1,2,2},
{2,5,5},
{2,3,4},
{1,4,1},
{4,3,3},
{3,5,1}
};
vert = 5;
list = new ArrayList<>();
parent = new int[vert + 1];
distance = new long[vert + 1];
for (int i = 0; i <= vert; i++) {
list.add(i, new LinkedList<Edge>());
}
for (int i = 0; i < neighbours.length; i++) {
int u = neighbours[i][0];
int v = neighbours[i][1];
int w = neighbours[i][2];
list.get(u).add(new Edge(v, w));
list.get(v).add(new Edge(u, w));
}
traverseBFS(0);
}
A simple print out the graph created shows that node 0 is not connected to any other node:
Node 0 connected: []
Node 1 connected: [to 2, to 4]
Node 2 connected: [to 1, to 5, to 3]
Node 3 connected: [to 2, to 4, to 5]
Node 4 connected: [to 1, to 3]
Node 5 connected: [to 2, to 3]
To simplify the printout add toString method to Edge:
static class Edge {
int to;
int weight;
public Edge(int a, int b) {
to = a;
weight = b;
}
#Override
public String toString() {
return "to "+to;
}
}
and use
for(int node = 0; node < list.size(); node ++){
System.out.println("Node "+node +" connected: " + list.get(node));
}
Related
Question to find Bfs path ,, i am able to code bfs path if the graph have vertices marked as 0,1,2,3,4,,like this
But can't able to apply adjacency matrix how to solve bfs for graph like 5,10,15,20
attached images what i have coded
solution
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Bfs {
public static void bfsTraversal(int[][] adjMatrix) {
Queue<Integer> pendingVertices = new LinkedList<>();
boolean[] visited = new boolean[adjMatrix.length];
visited[0] = true;
pendingVertices.add(0);
while (!pendingVertices.isEmpty()) {
int currentVertex = pendingVertices.poll();
System.out.print(currentVertex + " ");
for (int i = 0; i < adjMatrix.length; i++) {
if (adjMatrix[currentVertex][i] == 1 && !visited[i]) {
pendingVertices.add(i);
visited[i] = true;
}
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int v = s.nextInt();
int e = s.nextInt();
int[][] adjMatrix = new int[v][v];
for (int i = 0; i < e; i++) {
int v1 = s.nextInt();
int v2 = s.nextInt();
adjMatrix[v1][v2] = 1;
adjMatrix[v2][v1] = 1;
}
bfsTraversal(adjMatrix);
}
}
Click here for Question for bfs like vertices 0,1,2,3,4...
Click here for ,How i want to solve this for bfs like vertices 5,10,15,20...
And i want to do the same for graph like this ,,can't get logic
Solved by mapping the input with 0,1,2,3.... and maintained a reverseMap
Click here to view the Solution
If you know the range of the numbers, you can let the numbers 5, 10, 15 and 20 be the IDs of the nodes and store the indices of the nodes in a seperate array. Suppose the name of the array is IndexLookupArray, if you want to lookup the index of a node with ID x you can find it in IndexLookupArray[x]. And the rest of the code should be the same. If the range of the numbers is unknown or if it's too big to fit in an array, you can store the indices in a hash map for example and do the same thing.
You can write something like this:
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Bfs {
public static void bfsTraversal(int[][] adjMatrix) {
Queue<Integer> pendingVertices = new LinkedList<>();
boolean[] visited = new boolean[adjMatrix.length];
visited[0] = true;
pendingVertices.add(0);
while (!pendingVertices.isEmpty()) {
int currentVertex = pendingVertices.poll();
System.out.print(currentVertex + " ");
for (int i = 0; i < adjMatrix.length; i++) {
if (adjMatrix[currentVertex][i] == 1 && !visited[i]) {
pendingVertices.add(i);
visited[i] = true;
}
}
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int idx = 0;
int range = s.nextInt();
int v = s.nextInt();
int e = s.nextInt();
int[] IndexLookupArray = new int[range + 1]; // range + 1 since IndexLookupArray[range] should be accessible.
int[][] adjMatrix = new int[v][v];
Arrays.fill(IndexLookupArray, 0, range + 1, -1);
for (int i = 0; i < e; i++) {
int v1 = s.nextInt();
if (IndexLookupArray[v1] == -1)
{
IndexLookupArray[v1] = idx;
idx++;
}
v1 = IndexLookupArray[v1];
int v2 = s.nextInt();
if (IndexLookupArray[v2] == -1)
{
IndexLookupArray[v2] = idx;
idx++;
}
v2 = IndexLookupArray[v2];
adjMatrix[v1][v2] = 1;
adjMatrix[v2][v1] = 1;
}
bfsTraversal(adjMatrix);
}
}
There are various questions on how to find the number of cycles/circuits in a directed graph.I have mostly visited them, and i did come out with a code which does it.
I am struck at a point where my code doesn't give a cycle/circuit below of length 3.
Code:
public class CyclesInGraph {
// Graph modeled as list of edges
static int[][] graph =
{
{1, 2}, {2, 3}, {3, 4}, {4, 3},
{3, 1}
};
static List<int[]> cycles = new ArrayList<int[]>();
/**
* #param args
*/
public static void main(String[] args) {
for (int i = 0; i < graph.length; i++)
for (int j = 0; j < graph[i].length; j++)
{
findNewCycles(new int[] {graph[i][j]});
}
for (int[] cy : cycles)
{
String s = "" + cy[0];
for (int i = 1; i < cy.length; i++)
{
s += "," + cy[i];
}
o(s);
}
}
static void findNewCycles(int[] path)
{
int n = path[0];
int x;
int[] sub = new int[path.length + 1];
for (int i = 0; i < graph.length; i++)
for (int y = 0; y <= 1; y++)
if (graph[i][y] == n)
// edge refers to our current node
{
x = graph[i][(y + 1) % 2];
if (!visited(x, path))
// neighbor node not on path yet
{
sub[0] = x;
System.arraycopy(path, 0, sub, 1, path.length);
// explore extended path
findNewCycles(sub);
}
else if ((path.length > 2) && (x == path[path.length - 1]))
// cycle found
{
int[] p = normalize(path);
int[] inv = invert(p);
if (isNew(p) && isNew(inv))
{
cycles.add(p);
}
}
}
}
// check of both arrays have same lengths and contents
static Boolean equals(int[] a, int[] b)
{
Boolean ret = (a[0] == b[0]) && (a.length == b.length);
for (int i = 1; ret && (i < a.length); i++)
{
if (a[i] != b[i])
{
ret = false;
}
}
return ret;
}
// create a path array with reversed order
static int[] invert(int[] path)
{
int[] p = new int[path.length];
for (int i = 0; i < path.length; i++)
{
p[i] = path[path.length - 1 - i];
}
return normalize(p);
}
// rotate cycle path such that it begins with the smallest node
static int[] normalize(int[] path)
{
int[] p = new int[path.length];
int x = smallest(path);
int n;
System.arraycopy(path, 0, p, 0, path.length);
while (p[0] != x)
{
n = p[0];
System.arraycopy(p, 1, p, 0, p.length - 1);
p[p.length - 1] = n;
}
return p;
}
// compare path against known cycles
// return true, iff path is not a known cycle
static Boolean isNew(int[] path)
{
Boolean ret = true;
for(int[] p : cycles)
{
if (equals(p, path))
{
ret = false;
break;
}
}
return ret;
}
static void o(String s)
{
System.out.println(s);
}
// return the int of the array which is the smallest
static int smallest(int[] path)
{
int min = path[0];
for (int p : path)
{
if (p < min)
{
min = p;
}
}
return min;
}
// check if vertex n is contained in path
static Boolean visited(int n, int[] path)
{
Boolean ret = false;
for (int p : path)
{
if (p == n)
{
ret = true;
break;
}
}
return ret;
}
}
Output that I am getting:
1,3,2
But i should get 3,4 also as 3-4-3 also make a cycle in graph.
I would like to expand polynomial from form like this : (x - x1) (x-x2) (x-x3) ...
while I have x1,x2,x3... in form of array, to polynomial form like a x^3 + b x^2 + c , where arguments are in array.
For the logic of this, see what the expansions look like on Wolfram alpha (e.g. expand (x-a)(x-b)(x-c)(x-d)(x-e)).
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
// (x-5)(x-4)(x-3)(x-2)(x-7)
int[] xs = { 5, 4, 3, 2, 7 };
List<Integer> coefficients = new ArrayList<>();
boolean positive = true;
for (int i = 0; i < xs.length + 1; ++i) {
int coefficient = 0;
if (i > 0) {
List<int[]> combos = combos(xs, i);
for (int[] nums : combos) {
int product = 1;
for (int num : nums) {
product *= num;
}
coefficient += product;
}
} else {
coefficient = 1;
}
coefficients.add(coefficient * (positive ? 1 : -1));
positive = !positive;
}
for (int i = 0; i < coefficients.size(); ++i) {
int coefficient = coefficients.get(i);
int exponenent = (coefficients.size() - i - 1);
System.out.print(coefficient + "*x^" + exponenent + (exponenent == 0 ? "" : " + "));
}
}
// Combinations of xs size k
private static List<int[]> combos(int[] xs, int k)
{
List<int[]> result = new ArrayList<>();
for (ArrayList<Integer> comboIdxs : combine(xs.length, k)) {
int[] combo = new int[comboIdxs.size()];
for (int i = 0; i < comboIdxs.size(); ++i) {
combo[i] = xs[comboIdxs.get(i)];
}
result.add(combo);
}
return result;
}
// Thanks http://www.programcreek.com/2014/03/leetcode-combinations-java/
public static ArrayList<ArrayList<Integer>> combine(int n, int k) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (n <= 0 || n < k)
return result;
ArrayList<Integer> item = new ArrayList<Integer>();
dfs(n, k, 0, item, result); // because it need to begin from 1
return result;
}
private static void dfs(int n, int k, int start, ArrayList<Integer> item,
ArrayList<ArrayList<Integer>> res) {
if (item.size() == k) {
res.add(new ArrayList<Integer>(item));
return;
}
for (int i = start; i < n; i++) {
item.add(i);
dfs(n, k, i + 1, item, res);
item.remove(item.size() - 1);
}
}
}
I have designed a recursive algorithm to find the number of children in a string. The string is actually an array such as [1,0,1,0,1]. There three possible children of this string which are [0,0,1,0,1], [1,0,0,0,1] and [1,0,1,0,0]. Thus the criteria for creating the children is to decrement only one non-zero entry in the string. Since there are three non-zero entries in [1,0,1,0,1] so three possible children. Continuing in this fashion each children can now have two possible children and so on. The recursion stop when there is only one non-zero entry in the string.
This is my code:
public class Recursion {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] c={1,0,1,0,1};
System.out.println(num(c));
}
private static int num(int[] v){
if(numChildren(v)==1){
return 1;
}
else{
int[][] ge=children(v);
for(int[] e:ge){
return 1+num(e);
}
System.out.print("this return should never execute");
return 0;
}
}
private static int numChildren(int[] val){
int sum=0;
for(int i=0;i<val.length;i++){
if(val[i]!=0){
sum+=1;
}
}
return sum;
}
private static int[][] children(int[] p){
int pChildern=numChildren(p);
int[] d=new int[pChildern];
int[][] r=new int[pChildern][];
int c=0;
for(int j=0;j<p.length;j++){
if(p[j]!=0){
d[c]=j;
c++;
}
}
for(int i=0;i<pChildern;i++){
p[d[i]]--;
r[i]=p.clone();
p[d[i]]++;
}
return r;
}
}
My code does execute but doesn't produce correct result. It should print 6 but it prints 3.
Can any one suggest me what is wrong with this code?
// Returns size of subtree including the root
int getNumChilds(Node node) {
int count = 1;
for (Node child : node.getChildren()) {
count += getNumChilds(child);
}
return count;
}
I didn't really go into details, but this block looks weird:
int[][] ge=children(v);
for(int[] e:ge){
return 1+num(e);
}
System.out.print("this return should never execute");
return 0;
You want to sum up all its children here, but you return too early. It should be something like this:
int[][] ge=children(v);
int totChild = 0;
for(int[] e:ge){
totChild = totChild + num(e);
}
return totChild;
I think following code might be well suited to your needs.
{1, 0, 1, 0, 1} --> gives 7 (2 x 2 x 2 - 1)
{1, 1, 1, 1, 1} --> gives 31 (2 x 2 x 2 x 2 x 2 - 1)
{4, 4, 1, 1, 1} --> gives 199 (5 x 5 x 2 x 2 x 2 - 1)
-1 is to remove {0, 0, 0, 0, 0} from children.
public class Recursion {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
int[] c={4,4,1,1,1};
System.out.println(num(c, 0));
}
private static void print(int[] v) {
System.out.print("[");
for ( int i = 0; i < v.length; ++i ) {
System.out.print(v[i] + ",");
}
System.out.println("] ");
}
private static int num(int[] v, int k){
if(numChildren(v)==1){
return 1;
}
else{
int r = 1;
for ( int i = k; i < v.length; ++i ) {
if ( v[i] > 0) {
int o = v[i];
v[i] = o - 1;
print(v);
r += num(v, i);
v[i] = o;
}
}
return r;
}
}
private static int numChildren(int[] val){
int sum=0;
for(int i=0;i<val.length;i++){
if(val[i]!=0){
sum+=1;
}
}
return sum;
}
}
Grid Walking (Score 50 points):
You are situated in an N dimensional grid at position (x_1,x2,...,x_N). The dimensions of the grid are (D_1,D_2,...D_N). In one step, you can walk one step ahead or behind in any one of the N dimensions. (So there are always 2N possible different moves). In how many ways can you take M steps such that you do not leave the grid at any point? You leave the grid if you for any x_i, either x_i <= 0 or x_i > D_i.
Input:
The first line contains the number of test cases T. T test cases follow. For each test case, the first line contains N and M, the second line contains x_1,x_2...,x_N and the 3rd line contains D_1,D_2,...,D_N.
So, in the above solution I'm trying to take one dimensional array.
The website claims 38753340 to be the answer, but I'm not getting it.
public class GridWalking {
/**
* #param args
*/
public static void main(String[] args) {
try {
long arr[] = new long[78];
long pos = 44;
long totake = 287;
/*
* Double arr[] = new Double[3]; Double pos = 0; Double totake = 5;
*/
Double val = calculate(arr, pos, totake);
System.out.println(val % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
public static HashMap<String, Double> calculated = new HashMap<String, Double>();
private static Double calculate(long[] arr, long pos, long totake) {
if (calculated.containsKey(pos + "" + totake)) {
return calculated.get(pos + "" + totake);
}
if (0 == totake) {
calculated.put(pos + "" + totake, new Double(1));
return new Double(1);
}
if (pos == arr.length - 1) {
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
if (pos == 0) {
Double b = calculate(arr, pos + 1, totake - 1);
Double ret = b;
calculated.put(pos + "" + totake, new Double(ret));
return ret;
}
Double a = calculate(arr, pos + 1, totake - 1);
Double b = calculate(arr, pos - 1, totake - 1);
Double ret = (a + b);
calculated.put(pos + "" + totake, ret);
return ret;
}
}
You need to change key values as for pos + "_" + totake.
I have rewritten it but I'm not sure it working or not. It takes too much time to complete if ever.
public class GridWalking {
static long arr_length = 78;
static long pos = 44;
static long totake = 287;
static long count = 0;
/**
* #param args
*/
public static void main(String[] args) {
try {
calculate(pos, totake);
System.out.println(count % 1000000007);
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
private static void calculate(long pos, long totake) {
if (pos < 0 || pos > arr_length - 1)
return;
if (0 == totake) {
count++;
return;
}
calculate(pos + 1, totake - 1);
calculate(pos - 1, totake - 1);
}
}
I have tried solving that Grid walking problem in Hackerrank. this is the code that had worked(in ecclipse atleast). but i donno why it does not match with given answers. Nut i think you can get the idea from it. Since it does not use recursion, no problem with execution time..
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int count=0;
public static void main(String[] args) throws FileNotFoundException {
String filename = "src/testcases.txt";//testcases is just a file containing input
File file = new File(filename);
Scanner in = new Scanner(file);
//in.useDelimiter("[^0-9]+");
//-----------------------------------------------------------------
int T=in.nextInt();
for(int t=0;t<1;t++){
int N=in.nextInt();
int M=in.nextInt();System.out.println("M="+M);
int[] X=new int[N];
long max=1000000007;
int[] D=new int[N];
for(int i=0;i<N;i++) X[i]=in.nextInt();
for(int i=0;i<N;i++) D[i]=in.nextInt();
int Dmax=D[0];
int Dtotal=1;
for(int i=0;i<N;i++) if(Dmax<D[i]) Dmax=D[i];
for(int i=0;i<N;i++) X[i]--;
for(int i=0;i<N;i++) Dtotal*=D[i];//total number of fields
long[] mainarray= new long[Dtotal];
long[] mainarraynext=new long[Dtotal];
int[][] ways=new int[N][Dmax];
set( X, mainarray,D, 1);
int temp[]=new int[N];
for(int h=0;h<10;h++){
for(int j=0;j<Dtotal;j++){
mainarraynext[j]=getsum(inverse(j,D),mainarray, D );
}
for(int j=0;j<Dtotal;j++){
mainarray[j]=mainarraynext[j];
mainarray[j]%=max;
}
System.out.println(Arrays.toString(mainarray));
}
long finalsum=0;
for(int j=0;j<Dtotal;j++){
finalsum+=mainarray[j];
//System.out.println(finalsum);
}
System.out.println(finalsum);
//System.out.println(Arrays.toString(inverse(44,D)));
}
}
public static long get(int[] x, long[] mainarray, int[] D){
for(int i=0;i<x.length;i++){
if(x[i]>=D[i]) return 0;
if(x[i]<0) return 0;
}
int index=0;
for(int i=0;i<D.length;i++){
index=(index*D[i])+x[i];
}
return mainarray[index];
}
public static int[] inverse(int index,int[] D){
int[] temp=new int[D.length];
for(int i=D.length-1;i>=0;i--){
temp[i]=index%D[i];
index=index/D[i];
}
return temp;
}
public static void set(int[] x, long[] mainarray, int[] D, int value){
int index=0;
for(int i=0;i<D.length;i++){
index=(index*D[i])+x[i];
}
mainarray[index]=value;
}
public static long getsum(int[] x,long[] mainarray, int[] D ){
int[] temp=new int[x.length];
long sum=0;
//for 2n different sides
for(int j=0;j<x.length;j++){//sum in each side
temp[j]=x[j];
}
for(int j=0;j<x.length;j++){//sum in each side
temp[j]--;
sum+=get(temp, mainarray, D);
temp[j]+=2;
sum+=get(temp, mainarray, D);
temp[j]--;
}
return sum;
}
}
Here's a Java solution I've built for the original hackerrank problem. For big grids runs forever. Probably some smart math is needed.
long compute(int N, int M, int[] positions, int[] dimensions) {
if (M == 0) {
return 1;
}
long sum = 0;
for (int i = 0; i < N; i++) {
if (positions[i] < dimensions[i]) {
positions[i]++;
sum += compute(N, M - 1, positions, dimensions);
positions[i]--;
}
if (positions[i] > 1) {
positions[i]--;
sum += compute(N, M - 1, positions, dimensions);
positions[i]++;
}
}
return sum % 1000000007;
}