We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
I was in this problem a lot of hours until I began to read again the problem and there I found my error:
"Consider an undirected graph"
This was really important because in my case I was just connecting node "source" with "destination" but I didn't connect at the inverse.
So, this is the code
publicstaticclassGraph{HashMap<Integer,Node>nodeLookup=newHashMap<Integer,Node>();intsize;publicstaticclassNode{intid;LinkedList<Node>adjacent=newLinkedList<Node>();privateNode(intid){this.id=id;}}publicGraph(ints){this.size=s;for(inti=0;i<size;i++){Nodenode=newNode(i);nodeLookup.put(i,node);}}publicNodegetNode(intindex){returnnodeLookup.get(index);}publicvoidaddEdge(intfirst,intsecond){Nodes=getNode(first);Noded=getNode(second);s.adjacent.add(d);d.adjacent.add(s);//THIS IS KEY!!! This is an Unidirectional Graph}publicint[]shortestReach(intstartId){// 0 indexedint[]distance=newint[size];Arrays.fill(distance,-1);LinkedList<Node>toVisit=newLinkedList<Node>();HashSet<Integer>visited=newHashSet<Integer>();toVisit.add(getNode(startId));distance[startId]=0;while(!toVisit.isEmpty()){Nodecurrent=toVisit.remove();for(Noden:current.adjacent){if(!visited.contains(n.id)){visited.add(n.id);toVisit.add(n);distance[n.id]=distance[current.id]+6;}}}returndistance;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
BFS: Shortest Reach in a Graph
You are viewing a single comment's thread. Return to all comments →
This is my Java 7 Solution.
I was in this problem a lot of hours until I began to read again the problem and there I found my error:
"Consider an undirected graph"
This was really important because in my case I was just connecting node "source" with "destination" but I didn't connect at the inverse.
So, this is the code