-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFSindex0.java
More file actions
31 lines (26 loc) · 827 Bytes
/
BFSindex0.java
File metadata and controls
31 lines (26 loc) · 827 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
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> bfs = new ArrayList<>();
boolean visited[] = new boolean[V];
Queue<Integer> q = new LinkedList<>();
visited[0] = true;
q.add(0);
//BFS Begins
while(!q.isEmpty())
{
Integer node = q.poll();
bfs.add(node);
for(Integer iterate : adj.get(node))
{
if(visited[iterate] == false)
{
visited[iterate] = true;
q.add(iterate);
}
}
}
return bfs;
}
}