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.
It took me some time to realize that the edges are Bidirectional.
publicstaticList<Integer>bfs(intn,intm,List<List<Integer>>edges,ints){// first create my adjacentsList// will be an array of Set() of [n] positions where 0 is node 1Set<Integer>[]adjacents=newSet[n];for(inti=0;i<n;i++){adjacents[i]=newHashSet<Integer>();}edges.stream().forEach(e->{adjacents[e.get(0)-1].add(e.get(1));adjacents[e.get(1)-1].add(e.get(0));});// init response = int[] response = int[n];// complete with all -1.finalList<Integer>response=newArrayList<>(n);for(inti=0;i<n-1;i++){response.add(-1);}// a queue of arrays of two positions, one for the node id, the other for heightfinalQueue<int[]>queue=newLinkedList<>();queue.add(newint[]{s,0});finalSet<Integer>visited=newHashSet<>();while(!queue.isEmpty()){int[]aNode=queue.poll();if(visited.contains(aNode[0])){continue;}visited.add(aNode[0]);Set<Integer>thisNodeNeighbors=adjacents[(aNode[0]-1)];thisNodeNeighbors.forEach(e->{queue.add(newint[]{e,aNode[1]+1});});if(aNode[1]!=0){Integerdistance=aNode[1]*6;// todo extract to functionintresponsePosition=aNode[0]<s?aNode[0]-1:aNode[0]-2;response.set(responsePosition,distance);}}returnresponse;}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Breadth First Search: Shortest Reach
You are viewing a single comment's thread. Return to all comments →
JAVA 15
It took me some time to realize that the edges are Bidirectional.