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.
/*
* Complete the 'bfs' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER n
* 2. INTEGER m
* 3. 2D_INTEGER_ARRAY edges
* 4. INTEGER s
*/
public static List<Integer> bfs(int n, int m, List<List<Integer>> edges, int s) {
// Build adjacency list
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < n; i++) {
adj.add(new ArrayList<>());
}
for (List<Integer> edge : edges) {
int u = edge.get(0) - 1; // 0-based indexing
int v = edge.get(1) - 1;
adj.get(u).add(v);
adj.get(v).add(u);
}
// Distance array initialized to -1
int[] dist = new int[n];
Arrays.fill(dist, -1);
// BFS
Queue<Integer> q = new LinkedList<>();
q.add(s - 1);
dist[s - 1] = 0;
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adj.get(u)) {
if (dist[v] == -1) {
dist[v] = dist[u] + 6; // edge weight = 6
q.add(v);
}
}
}
// Prepare result (excluding source node)
List<Integer> result = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (i != (s - 1)) {
result.add(dist[i]);
}
}
return result;
}
}
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 →
import java.util.*;
class ResultAlt {
}