-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dijkstra.java
78 lines (67 loc) · 1.96 KB
/
Dijkstra.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.ArrayDeque;
import java.util.Comparator;
import java.util.Deque;
import java.util.PriorityQueue;
/**
* Created by paulp on 10/15/2015.
*/
public class Dijkstra {
private double[] distTo;
private int[] parent;
private boolean[] marked;
private PriorityQueue<Integer> pq;
private class VertexComp implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if (distTo[o1] < distTo[o2]) return -1;
return 1;
}
}
public Dijkstra(WeightedDigraph G, int source) {
distTo = new double[G.V()];
parent = new int[G.V()];
marked = new boolean[G.V()];
for (int i = 0; i < G.V(); ++i) {
distTo[i] = Double.POSITIVE_INFINITY;
parent[i] = -1;
}
parent[source] = source;
distTo[source] = 0.0;
pq = new PriorityQueue<>(new VertexComp());
pq.add(source);
while (!pq.isEmpty()) {
int top = pq.poll();
if (!marked[top])
relax(G, top);
}
}
private void relax(WeightedDigraph G, int v) {
marked[v] = true;
for (DirectedWeightedEdge e : G.adj(v)) {
if (distTo[e.to()] > distTo[v] + e.weight()) {
distTo[e.to()] = distTo[v] + e.weight();
parent[e.to()] = v;
if (!pq.contains(e.to())) pq.add(e.to());
else{
pq.remove(e.to());
pq.add(e.to());
}
}
}
}
public boolean hasPathTo(int v) {
return parent[v] != -1;
}
public Iterable<Integer> pathTo(int v) {
Deque<Integer> stack = new ArrayDeque<>();
int ptr = v;
for (; ptr != parent[ptr]; ptr = parent[ptr]) {
stack.push(ptr);
}
stack.push(ptr);
return stack;
}
public double distanceTo(int v){
return distTo[v];
}
}