-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstra.java
More file actions
80 lines (64 loc) · 2.26 KB
/
Copy pathDijkstra.java
File metadata and controls
80 lines (64 loc) · 2.26 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
79
/*************************************************************************
* Dijkstra's algorithm.
*
*************************************************************************/
public class Dijkstra {
private static double INFINITY = Double.MAX_VALUE;
private static double EPSILON = 0.000001;
private EuclideanGraph G;
private double[] dist;
private int[] pred;
public Dijkstra(EuclideanGraph G) {
this.G = G;
}
// return shortest path distance from s to d
public double distance(int s, int d) {
dijkstra(s, d);
return dist[d];
}
// print shortest path from s to d (interchange s and d to print in right order)
public void showPath(int d, int s) {
dijkstra(s, d);
if (pred[d] == -1) {
System.out.println(d + " is unreachable from " + s);
return;
}
for (int v = d; v != s; v = pred[v])
System.out.print(v + "-");
System.out.println(s);
}
// Dijkstra's algorithm to find shortest path from s to d
private void dijkstra(int s, int d) {
int V = G.V();
// initialize
dist = new double[V];
pred = new int[V];
for (int v = 0; v < V; v++) dist[v] = INFINITY;
for (int v = 0; v < V; v++) pred[v] = -1;
// priority queue
IndexPQ pq = new IndexPQ(V);
for (int v = 0; v < V; v++) pq.insert(v, dist[v]);
// set distance of source
dist[s] = 0.0;
pred[s] = s;
pq.change(s, dist[s]);
// run Dijkstra's algorithm
while (!pq.isEmpty()) {
int v = pq.delMin();
//// System.out.println("process " + v + " " + dist[v]);
// v not reachable from s so stop
if (pred[v] == -1) break;
// scan through all nodes w adjacent to v
IntIterator i = G.neighbors(v);
while (i.hasNext()) {
int w = i.next();
if (dist[v] + G.distance(v, w) < dist[w] - EPSILON) {
dist[w] = dist[v] + G.distance(v, w);
pq.change(w, dist[w]);
pred[w] = v;
//// System.out.println(" lower " + w + " to " + dist[w]);
}
}
}
}
}