diff --git a/Data-Structures/Graphs/BFS.java b/Data-Structures/Graphs/BFS.java index 21da5fe..617df1a 100644 --- a/Data-Structures/Graphs/BFS.java +++ b/Data-Structures/Graphs/BFS.java @@ -7,29 +7,34 @@ static void addEdge(ArrayList> adj, int i, int j) { adj.get(j).add(i); } - static ArrayList bfs(ArrayList> adj) { - int v = adj.size(); - boolean[] visited = new boolean[v]; - ArrayList res = new ArrayList<>(); - Queue q = new LinkedList<>(); - - int src = 0; - visited[src] = true; - q.add(src); - - while (!q.isEmpty()) { - int curr = q.poll(); - res.add(curr); - - for (int x : adj.get(curr)) { - if (!visited[x]) { - visited[x] = true; - q.add(x); - } - } - } - - return res; + static ArrayList bfs(ArrayList> adj) { + int v = adj.size(); + // BFS forest traversal: iterate vertices in index order so disconnected + // components are also visited in a deterministic output order. + boolean[] visited = new boolean[v]; + ArrayList res = new ArrayList<>(); + + for (int s = 0; s < v; s++) { + if (!visited[s]) { + Queue q = new LinkedList<>(); + visited[s] = true; + q.add(s); + + while (!q.isEmpty()) { + int curr = q.poll(); + res.add(curr); + + for (int x : adj.get(curr)) { + if (!visited[x]) { + visited[x] = true; + q.add(x); + } + } + } + } + } + + return res; } public static void main(String[] args) {