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.
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner scanner = new Scanner(System.in);
int q = scanner.nextInt();
while (q-- > 0){
int n = scanner.nextInt();
int m = scanner.nextInt();
Graph graph = new Graph(n);
for (int i = 0; i < m; i++){
int u = scanner.nextInt();
int v = scanner.nextInt();
graph.addEdge(u, v);
}
int start = scanner.nextInt();
int[] distances = graph.bfs(start);
for (int i = 1; i <= n; i++){
if (i != start){
System.out.print(distances[i] + " ");
}
}
System.out.println();
}
scanner.close();
}
}
class Graph {
private final Map> adjList = new HashMap<>();
private final int numNodes;
public Graph(int numNodes){
this.numNodes = numNodes;
for (int i = 1; i <= numNodes; i++){
adjList.put(i, new ArrayList<>());
}
}
public void addEdge(int u, int v){
adjList.get(u).add(v);
adjList.get(v).add(u);
}
public int[] bfs(int start){
int[] distances = new int[numNodes + 1];
Arrays.fill(distances, -1);
Queue<Integer> queue = new LinkedList<>();
Set<Integer> visited = new HashSet<>();
queue.add(start);
visited.add(start);
distances[start] = 0;
while (!queue.isEmpty()){
int current = queue.poll();
for (int neighbor : adjList.get(current)){
if (!visited.contains(neighbor)){
visited.add(neighbor);
distances[neighbor] = distances[current] + 6;
queue.add(neighbor);
}
}
}
return distances;
}
}
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 →
Java Solution using a Graph class:
public class Solution {
}
class Graph { private final Map> adjList = new HashMap<>(); private final int numNodes;
}