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.
importjava.io.*;importjava.util.*;publicclassSolution{publicstaticvoidmain(String[]args){/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */Scannersc=newScanner(System.in);intqueryCount=sc.nextInt();for(inti=0;i<queryCount;++i){intnodeCount=sc.nextInt();intedgeCount=sc.nextInt();HashMap<Integer,ArrayList<Integer>>edges=newHashMap<Integer,ArrayList<Integer>>();for(intj=0;j<edgeCount;++j){intfrom=sc.nextInt();intto=sc.nextInt();ArrayList<Integer>values=newArrayList<Integer>();if(edges.containsKey(from)){values=edges.get(from);}values.add(to);edges.put(from,values);values=newArrayList<Integer>();if(edges.containsKey(to)){values=edges.get(to);}values.add(from);edges.put(to,values);}intheadNode=sc.nextInt();for(intj=1;j<=nodeCount;++j){Queue<Integer>queue=newLinkedList<Integer>();Booleanfound=false;if(j!=headNode){queue.add(headNode);HashMap<Integer,Boolean>visited=newHashMap<Integer,Boolean>();visited.put(headNode,true);intdist=0;while(!queue.isEmpty()&&!found){intsize=queue.size();while(size>0){inttemp=queue.poll();if(temp==j){found=true;System.out.print(dist+" ");break;}else{if(edges.containsKey(temp)){ArrayList<Integer>relatives=edges.get(temp);for(intk=0;k<relatives.size();++k){if(!visited.containsKey(relatives.get(k))){queue.add(relatives.get(k));visited.put(relatives.get(k),true);}}}}--size;}dist+=6;}if(!found){System.out.print(-1+" ");}}}System.out.println();}sc.close();}}
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
You are viewing a single comment's thread. Return to all comments →