-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24_BFS.java
More file actions
45 lines (40 loc) · 1.16 KB
/
24_BFS.java
File metadata and controls
45 lines (40 loc) · 1.16 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
import java.util.*;
public class BFS {
private int vertices;
private LinkedList<Integer>[] adjList;
BFS(int v) {
vertices = v;
adjList = new LinkedList[v];
for (int i = 0; i < v; i++)
adjList[i] = new LinkedList<>();
}
void addEdge(int src, int dest) {
adjList[src].add(dest);
}
void bfs(int start) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);
System.out.print("BFS Traversal: ");
while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + " ");
for (int adj : adjList[node]) {
if (!visited[adj]) {
visited[adj] = true;
queue.add(adj);
}
}
}
}
public static void main(String[] args) {
BFS graph = new BFS(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
System.out.println("Graph BFS starting from node 0:");
graph.bfs(0);
}
}