-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
64 lines (48 loc) · 1.72 KB
/
BFS.java
File metadata and controls
64 lines (48 loc) · 1.72 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
57
58
59
60
61
62
63
64
import java.util.LinkedList;
import java.util.Queue;
public class BFS {
private static class Graph {
private int vertices;
private LinkedList<Integer>[] adjacencyList;
public Graph(int vertices) {
this.vertices = vertices;
adjacencyList = new LinkedList[vertices];
for (int i = 0; i < vertices; i++) {
adjacencyList[i] = new LinkedList<>();
}
}
public void addEdge(int source, int destination) {
adjacencyList[source].add(destination);
}
public void bfs(int startVertex) {
boolean[] visited = new boolean[vertices];
Queue<Integer> queue = new LinkedList<>();
visited[startVertex] = true;
queue.add(startVertex);
while (!queue.isEmpty()) {
int currentVertex = queue.poll();
System.out.print(currentVertex + " ");
LinkedList<Integer> adjacentVertices = adjacencyList[currentVertex];
for (int adjacentVertex : adjacentVertices) {
if (!visited[adjacentVertex]) {
visited[adjacentVertex] = true;
queue.add(adjacentVertex);
}
}
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(6);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 4);
graph.addEdge(3, 4);
graph.addEdge(3, 5);
System.out.println("BFS traversal starting from vertex 0:");
graph.bfs(0);
System.out.println();
}
}