-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstSearchShortestPath.java
More file actions
57 lines (50 loc) · 1.71 KB
/
BreadthFirstSearchShortestPath.java
File metadata and controls
57 lines (50 loc) · 1.71 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
package graph_algorithms;
import data_structures.LinkedList;
import data_structures.Queue;
public class BreadthFirstSearchShortestPath extends ShortestPath {
public static void main(String[] args) {
// Example:
Graph graph = new AdjacencyListGraph(9, true);
graph.addEdge(0, 1);
graph.addEdge(1, 3);
graph.addEdge(1, 4);
graph.addEdge(2, 0);
graph.addEdge(2, 5);
graph.addEdge(2, 6);
graph.addEdge(3, 2);
graph.addEdge(3, 4);
graph.addEdge(4, 7);
graph.addEdge(4, 8);
graph.addEdge(6, 3);
graph.addEdge(7, 3);
graph.addEdge(7, 8);
System.out.println(breadthFirstSearchShortestPath(graph, 0, 7)); // [0, 1, 4, 7]
}
public static LinkedList<Integer> breadthFirstSearchShortestPath(Graph graph, int from, int to) {
Queue<Integer> queue = new LinkedList<>();
int vertexCount = graph.getVertexCount();
int[] distance = new int[vertexCount];
int[] predecessor = new int[vertexCount];
for (int i = 0; i < vertexCount; ++i) {
distance[i] = Integer.MAX_VALUE;
}
distance[from] = 0;
queue.enqueue(from);
outer:
while (queue.front() != null) {
int u = queue.dequeue();
for (int v : graph.outEdges(u)) {
if (distance[v] != Integer.MAX_VALUE) {
continue;
}
queue.enqueue(v);
distance[v] = distance[u] + 1;
predecessor[v] = u;
if (v == to) {
break outer;
}
}
}
return ShortestPath.backtrack(predecessor, from, to);
}
}