-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFStree.java
More file actions
32 lines (27 loc) · 914 Bytes
/
Copy pathBFStree.java
File metadata and controls
32 lines (27 loc) · 914 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class BFStree {
public ArrayList<Integer> bfsOfGraph(int V, ArrayList<ArrayList<Integer>> adj) {
ArrayList<Integer> bfs = new ArrayList<>();
boolean[] visited = new boolean[V];
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < V; i++) {
if (!visited[i]) {
q.add(i);
visited[i] = true;
while (!q.isEmpty()) {
Integer node = q.poll();
bfs.add(node);
for (Integer neighbor : adj.get(node)) {
if (!visited[neighbor]) {
visited[neighbor] = true;
q.add(neighbor);
}
}
}
}
}
return bfs;
}
}