-
Notifications
You must be signed in to change notification settings - Fork 187
/
BFS
43 lines (20 loc) · 824 Bytes
/
BFS
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
33
34
35
36
37
38
39
40
41
42
43
class Solution {
// Function to return Breadth First Traversal of given graph.
public ArrayList<Integer> bfsOfGraph(int v, ArrayList<ArrayList<Integer>> adj) {
// Code here
ArrayList<Integer> ans=new ArrayList<>();
boolean visited[]=new boolean[v+1];
Queue<Integer> q=new LinkedList<>();
q.add(0);
while(!q.isEmpty()){
int node=q.poll();
if(visited[node]) continue;
visited[node]=true;
ans.add(node);
for(int i:adj.get(node)){
q.add(i);
}
}
return ans;
}
}