-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS
More file actions
44 lines (34 loc) · 1.03 KB
/
Copy pathBFS
File metadata and controls
44 lines (34 loc) · 1.03 KB
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
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
public class bfs {
public ArrayList<Integer> bfsOfGraph(int v, ArrayList<ArrayList<Integer>>adj) {
ArrayList<Integer> bfs=new ArrayList<>();
boolean vis[] =new boolean[v];
Queue<Integer> q=new LinkedList<>();
q.add(0);
vis[0]=true;
while(!q.isEmpty()){
Integer node=q.poll();
bfs.add(node);
for(Integer it:adj.get(node)){
if(vis[it]==false){
vis[it]=true;
q.add(it);
}
}
}
return bfs;
}
public static void main(String[] args) {
int v = 5;
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for (int i = 0; i < v; i++) adj.add(new ArrayList<>());
adj.get(0).add(1);
adj.get(0).add(2);
adj.get(1).add(3);
adj.get(2).add(4);
bfs obj = new bfs();
System.out.println(obj.bfsOfGraph(v, adj));
}
}