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.
Java solution below. BFS can be used for single source shortest distances in unweighted graphs, which is what this is. Build an adjacency list for city roads (since this graph is sparse, we'd want to be looking for nonexistence of city roads rather than existance of village roads during BFS, for efficiency). Keep track of unvisited nodes with a set.
staticint[]rustMurderer(intn,int[][]roads,ints){// Build Adjacency ListList<Set<Integer>>cityRoads=newArrayList<>();for(inti=0;i<n;i++){cityRoads.add(newHashSet<>());}intnumRoads=roads.length;for(inti=0;i<numRoads;i++){intvertex1=roads[i][0];intvertex2=roads[i][1];cityRoads.get(vertex1-1).add(vertex2-1);cityRoads.get(vertex2-1).add(vertex1-1);}// Initialization for BFSint[]result=newint[n];result[s-1]=-1;// Use -1 to Indicate Source// Add Immediate Neighbors of Source to QueueQueue<Integer>BFSqueue=newLinkedList<>();Set<Integer>unvisited=newHashSet<>();for(inti=1;i<=n;i++){if(i!=s){if(!cityRoads.get(s-1).contains(i-1)){//System.out.println("Source Neighbor Added =" + (i));result[i-1]=1;BFSqueue.add(i);}else{unvisited.add(i);}}}// BFS for Shortest DistintcurrentLevel=1;while(!BFSqueue.isEmpty()){intcurrentNode=BFSqueue.poll();// Not At Same Level as Before, Increment Levelif(result[currentNode-1]!=currentLevel){++currentLevel;}//Add Valid Neighbors to Queue if Not Already VisitedIterator<Integer>currentUnvisited=unvisited.iterator();while(currentUnvisited.hasNext()){inti=currentUnvisited.next();if(!cityRoads.get(currentNode-1).contains(i-1)){// Can Go To This Noderesult[i-1]=currentLevel+1;BFSqueue.add(i);currentUnvisited.remove();}}}// Build Output Array and Returnint[]output=newint[n-1];booleanpassedS=false;for(inti=0;i<n;i++){if(result[i]==-1){passedS=true;continue;}output[passedS?i-1:i]=result[i];}returnoutput;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Rust & Murderer
You are viewing a single comment's thread. Return to all comments →
Java solution below. BFS can be used for single source shortest distances in unweighted graphs, which is what this is. Build an adjacency list for city roads (since this graph is sparse, we'd want to be looking for nonexistence of city roads rather than existance of village roads during BFS, for efficiency). Keep track of unvisited nodes with a set.