-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphBFS.java
More file actions
56 lines (51 loc) · 1.74 KB
/
Copy pathGraphBFS.java
File metadata and controls
56 lines (51 loc) · 1.74 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.ArrayList;
import java.util.LinkedList;
public class GraphBFS {
static void addEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) {
// for undirected connect u and v and then v and u
adj.get(u).add(v);
adj.get(v).add(u);
}
static void bfs(ArrayList<ArrayList<Integer>> adj, int v) {
boolean []visited = new boolean[v+1];
for(int i = 1; i < v + 1; i++) {
visited[i] = false;
}
int source = 1;
visited[source] = true;
LinkedList<Integer> queue = new LinkedList<>();
queue.add(source);
while(queue.size() != 0) {
// pop front element of queue
source = queue.poll();
System.out.print(source + ",");
// get number of adjacent vertices of current source
int size = adj.get(source).size();
for(int i = 0; i < size; i++) {
// get adjacent node
int adjNode = adj.get(source).get(i);
// check if adj node is visited or not
if(visited[adjNode] == false) {
visited[adjNode] = true;
queue.add(adjNode);
}
}
}
}
public static void main(String[] args) {
int V = 6;
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
for(int i = 0; i < V+1; i++) {
adj.add(new ArrayList<>());
}
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 2, 4);
addEdge(adj, 2, 5);
addEdge(adj, 3, 5);
addEdge(adj, 4, 5);
addEdge(adj, 4, 6);
addEdge(adj, 5, 6);
bfs(adj, V);
}
}