-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraSP.java
More file actions
78 lines (55 loc) · 1.58 KB
/
DijkstraSP.java
File metadata and controls
78 lines (55 loc) · 1.58 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class DijkstraSP {
private DirectedEdge[] edgeTo;
private double[] distTo;
private IndexMinPQ<DirectedEdge> pq;
private final double ZERO = 0.0;
public DijkstraSP(EdgeWeightedDigraph G, int s) {
int nrVertices = G.V();
edgeTo = new DirectedEdge[nrVertices];
distTo = new Double[nrVertices];
pq = new IndexMinPQ<Double>(nrVertices);
for (int i = 0; i < nrVertices; i++) {
distTo[i] = Double.Positive_Infinity;
}
distTo[s]= ZERO; // Distance from source to itself is zero.
pq.insert(s,ZERO);
while (!pq.isEmpty())
{
int v = pq.delMin();
for (DirectedEdge e : G.adj(v))
relax(e);
}
}
public void relax(DirectedEdge e) {
int v = e.from(); int w = e.to();
if (distTo[w] > distTo[v] + e.weight())
{
edgeTo[w]= e;
distTo[w] = distTo[v] + e.weight();
if (pq.contains(w))
pq.decreaseKey(w, distTo[w]);
else
pq.insert(w, distTo[w]);
}
}
public double distTo(int v) { return distTo[v]; }
public boolean hasPathTo(int v) {return distTo[v] < Double.Positive_Infinity ;}
public void relax(EdgeWeightedDigraph G, int v) {
for (DirectedEdge e : G.adj(v)) {
int w = e.to();
if(distTo[w] > distTo[v] + e.weight())
{
edgeTo[w] = e;
distTo[w] = distTo[v] + e.weight();
}
}
}
public Iterable<DirectedEdge> pathTo(v) {
if (!hasPathTo(v)) return null;
Stack<DirectedEdge> path = new Stack<DirectedEdge>();
for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()] ) {
path.push(e);
}
return path;
}
}