-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstSearch.java
More file actions
51 lines (46 loc) · 1.52 KB
/
BreadthFirstSearch.java
File metadata and controls
51 lines (46 loc) · 1.52 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
package graph_algorithms;
import data_structures.LinkedList;
import data_structures.Queue;
public class BreadthFirstSearch {
@SuppressWarnings("DuplicatedCode")
public static void main(String[] args) {
// Example:
Graph graph = new AdjacencyMatrixGraph(10, true);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 3);
graph.addEdge(5, 3);
graph.addEdge(6, 3);
graph.addEdge(6, 5);
graph.addEdge(7, 8);
graph.addEdge(8, 9);
graph.addEdge(9, 7);
breadthFirstSearch(graph);
}
public static void breadthFirstSearch(Graph graph) {
Queue<Integer> queue = new LinkedList<>();
LinkedList<Integer> visited = new LinkedList<>(); // TODO: Use Dictionary once AVLTree is finished
int vertexCount = graph.getVertexCount();
for (int s = 0; s < vertexCount; ++s) {
if (visited.contains(s)) {
continue;
}
queue.enqueue(s);
while (queue.front() != null) {
int u = queue.dequeue();
if (!visited.contains(u)) {
visited.addLast(u);
for (int v : graph.outEdges(u)) {
if (visited.contains(v)) {
continue;
}
queue.enqueue(v);
}
}
}
}
}
}