-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
62 lines (55 loc) · 2.05 KB
/
Dijkstra.java
File metadata and controls
62 lines (55 loc) · 2.05 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
package graph_algorithms;
import data_structures.KeyedHeap;
import data_structures.KeyedPriorityQueue;
import data_structures.LinkedList;
public class Dijkstra extends ShortestPath {
public static void main(String[] args) {
// Example:
Graph graph = new AdjacencyListGraph(9, true);
graph.addEdge(0, 1, 1);
graph.addEdge(1, 3, 2);
graph.addEdge(1, 4, 4);
graph.addEdge(2, 0, 8);
graph.addEdge(2, 5, 2);
graph.addEdge(2, 6, 6);
graph.addEdge(3, 2, 4);
graph.addEdge(3, 4, 1);
graph.addEdge(4, 7, 1);
graph.addEdge(4, 8, 5);
graph.addEdge(6, 3, 5);
graph.addEdge(7, 3, 2);
graph.addEdge(7, 8, 3);
System.out.println(dijkstra(graph, 0, 7)); // [0, 1, 3, 4, 7]
}
public static LinkedList<Integer> dijkstra(Graph graph, int from, int to) {
int vertexCount = graph.getVertexCount();
double[] distance = new double[vertexCount];
int[] predecessor = new int[vertexCount];
for (int i = 0; i < vertexCount; ++i) {
distance[i] = Double.POSITIVE_INFINITY;
}
distance[from] = 0;
LinkedList<Integer> visited = new LinkedList<>(); // TODO: Use Dictionary once AVLTree is finished
KeyedPriorityQueue<Integer> prioQueue = new KeyedHeap<>();
for (int i = 0; i < graph.getVertexCount(); ++i) {
prioQueue.insert(i, distance[i]);
}
while (visited.size() != vertexCount) {
int u = prioQueue.extractMin();
visited.addLast(u);
for (int v : graph.outEdges(u)) {
if (visited.contains(v)) {
continue;
}
double d1 = distance[v];
double d2 = distance[u] + graph.cost(u, v);
if (d2 < d1) {
distance[v] = d2;
prioQueue.decreaseKey(v, d2);
predecessor[v] = u;
}
}
}
return ShortestPath.backtrack(predecessor, from, to);
}
}