-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFS_Graph.java
More file actions
30 lines (27 loc) · 847 Bytes
/
BFS_Graph.java
File metadata and controls
30 lines (27 loc) · 847 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
class Solution {
// Function to return Breadth First Traversal of given graph.
public ArrayList<Integer> bfsOfGraph(ArrayList<ArrayList<Integer>> adj) {
Queue<Integer> queue= new LinkedList<>();
ArrayList<Integer> bfs = new ArrayList<>();
int c=0;
for(ArrayList<Integer> sublist : adj){
if(!sublist.isEmpty()){
c++;
}
}
boolean vis[] = new boolean[c+1];
queue.add(0);
vis[0] = true;
while(!queue.isEmpty()){
Integer node = queue.poll();
bfs.add(node);
for(Integer it:adj.get(node)){
if(vis[it] == false){
vis[it]=true;
queue.add(it);
}
}
}
return bfs;
}
}