-
Notifications
You must be signed in to change notification settings - Fork 164
/
GraphBFS.java
78 lines (63 loc) · 1.8 KB
/
GraphBFS.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//Contributed by: @with-mahimasingh
import java.io.*;
import java.util.*;
public class graph_bfs {
static ArrayList<Integer> bfsGraph(int V, ArrayList<ArrayList<Integer>>adj)
{
ArrayList<Integer> bfs= new ArrayList<>();
boolean[] vis= new boolean[V+1];
for(int i=1;i<=V;i++)
{
if(!vis[i])
{
Queue<Integer> q=new LinkedList<>();
q.add(i);
vis[i]=true;
while(!q.isEmpty())
{
Integer node=q.poll();
bfs.add(node);
for(int j:adj.get(node))
{
if(vis[j]==false)
{
vis[j]=true;
q.add(j);
}
}
}
}
}
return bfs;
}
public static void main(String[] args) throws IOException {
ArrayList<ArrayList<Integer>> adj= new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st= new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
for(int i=1;i<=n+1;i++)
adj.add(new ArrayList<>());
adj.get(1).add(2);
adj.get(2).add(1);
adj.get(2).add(3);
adj.get(2).add(7);
adj.get(3).add(2);
adj.get(3).add(5);
adj.get(4).add(6);
adj.get(5).add(3);
adj.get(5).add(7);
adj.get(6).add(4);
adj.get(7).add(5);
adj.get(7).add(2);
System.out.println("BFS Traversal is: ");
ArrayList<Integer> result= bfsGraph(n,adj);
System.out.println(result);
}
}
/* Graph structure here:
1--2 4--6
| \
| 3
| |
7--5
*/