-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDijkstraSP.java
More file actions
255 lines (231 loc) · 9.34 KB
/
DijkstraSP.java
File metadata and controls
255 lines (231 loc) · 9.34 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/******************************************************************************
*
* Revised Dijkstra's algorithm to adapt to solving the lowest latency network problem. Computes the shortest path .
* Assumes all weights are nonnegative.
*
/**
* The {@code DijkstraSP} class represents a data type for solving the
* single-source shortest paths problem in edge-weighted digraphs
* where the edge weights are nonnegative.
* <p>
* This implementation uses Dijkstra's algorithm with a binary heap.
* The constructor takes time proportional to <em>E</em> log <em>V</em>,
* where <em>V</em> is the number of vertices and <em>E</em> is the number of edges.
* Each call to {@code distTo(int)} and {@code hasPathTo(int)} takes constant time;
* each call to {@code pathTo(int)} takes time proportional to the number of
* edges in the shortest path returned.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/44sp">Section 4.4</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*
* @author Runyuan Yan
*/
public class DijkstraSP {
private double[] distTo; // distTo[v] = distance of shortest s->v path
private DirectedEdge[] edgeTo; // edgeTo[v] = last edge on shortest s->v path
private IndexMinPQ<Double> pq; // priority queue of vertices
/**
* Computes a shortest-paths tree from the source vertex {@code s} to every other
* vertex in the edge-weighted digraph {@code G}.
*
* @param G the edge-weighted digraph
* @param s the source vertex
* @throws IllegalArgumentException if an edge weight is negative
* @throws IllegalArgumentException unless {@code 0 <= s < V}
*/
public DijkstraSP(EdgeWeightedDigraph G, int s) {
for (DirectedEdge e : G.edges()) {
if (e.latency() < 0)
throw new IllegalArgumentException("edge " + e + " has negative weight");
}
distTo = new double[G.V()];
edgeTo = new DirectedEdge[G.V()];
validateVertex(s);
for (int v = 0; v < G.V(); v++)
distTo[v] = Double.POSITIVE_INFINITY;
distTo[s] = 0.0;
// relax vertices in order of distance from s
pq = new IndexMinPQ<Double>(G.V());
pq.insert(s, distTo[s]);
while (!pq.isEmpty()) {
int v = pq.delMin();
for (DirectedEdge e : G.adj(v))
relax(e);
}
// check optimality conditions
assert check(G, s);
}
// relax edge e and update pq if changed
private void relax(DirectedEdge e) {
int v = e.from(), w = e.to();
if (distTo[w] > distTo[v] + e.latency()) {
distTo[w] = distTo[v] + e.latency();
edgeTo[w] = e;
if (pq.contains(w)) pq.decreaseKey(w, distTo[w]);
else pq.insert(w, distTo[w]);
}
}
/**
* Returns the length of a shortest path from the source vertex {@code s} to vertex {@code v}.
* @param v the destination vertex
* @return the length of a shortest path from the source vertex {@code s} to vertex {@code v};
* {@code Double.POSITIVE_INFINITY} if no such path
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public double distTo(int v) {
validateVertex(v);
return distTo[v];
}
/**
* Returns true if there is a path from the source vertex {@code s} to vertex {@code v}.
*
* @param v the destination vertex
* @return {@code true} if there is a path from the source vertex
* {@code s} to vertex {@code v}; {@code false} otherwise
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public boolean hasPathTo(int v) {
validateVertex(v);
return distTo[v] < Double.POSITIVE_INFINITY;
}
/**
* Returns a shortest path from the source vertex {@code s} to vertex {@code v}.
*
* @param v the destination vertex
* @return a shortest path from the source vertex {@code s} to vertex {@code v}
* as an iterable of edges, and {@code null} if no such path
* @throws IllegalArgumentException unless {@code 0 <= v < V}
*/
public ArrayList<DirectedEdge> pathTo(int v) {
validateVertex(v);
if (!hasPathTo(v)) return null;
ArrayList<DirectedEdge> path = new ArrayList<DirectedEdge>();
for (DirectedEdge e = edgeTo[v]; e != null; e = edgeTo[e.from()]) {
//System.out.println(e);
path.add(e);
}
return path;
}
// check optimality conditions:
// (i) for all edges e: distTo[e.to()] <= distTo[e.from()] + e.weight()
// (ii) for all edge e on the SPT: distTo[e.to()] == distTo[e.from()] + e.weight()
private boolean check(EdgeWeightedDigraph G, int s) {
// check that edge weights are nonnegative
for (DirectedEdge e : G.edges()) {
if (e.latency() < 0) {
System.err.println("negative edge weight detected");
return false;
}
}
// check that distTo[v] and edgeTo[v] are consistent
if (distTo[s] != 0.0 || edgeTo[s] != null) {
System.err.println("distTo[s] and edgeTo[s] inconsistent");
return false;
}
for (int v = 0; v < G.V(); v++) {
if (v == s) continue;
if (edgeTo[v] == null && distTo[v] != Double.POSITIVE_INFINITY) {
System.err.println("distTo[] and edgeTo[] inconsistent");
return false;
}
}
// check that all edges e = v->w satisfy distTo[w] <= distTo[v] + e.weight()
for (int v = 0; v < G.V(); v++) {
for (DirectedEdge e : G.adj(v)) {
int w = e.to();
if (distTo[v] + e.latency() < distTo[w]) {
System.err.println("edge " + e + " not relaxed");
return false;
}
}
}
// check that all edges e = v->w on SPT satisfy distTo[w] == distTo[v] + e.weight()
for (int w = 0; w < G.V(); w++) {
if (edgeTo[w] == null) continue;
DirectedEdge e = edgeTo[w];
int v = e.from();
if (w != e.to()) return false;
if (distTo[v] + e.latency() != distTo[w]) {
System.err.println("edge " + e + " on shortest path not tight");
return false;
}
}
return true;
}
// throw an IllegalArgumentException unless {@code 0 <= v < V}
private void validateVertex(int v) {
int V = distTo.length;
if (v < 0 || v >= V)
throw new IllegalArgumentException("vertex " + v + " is not between 0 and " + (V-1));
}
/*calculates the total bandwidth on a given list of edges
*/
public int bandwidth(ArrayList<DirectedEdge> path)
{
int bandWidth =0;
for(DirectedEdge e:path)
{
bandWidth += e.bandWidth();
}
return bandWidth;
}
/**
* Unit tests the {@code DijkstraSP} data type.
*
* @param args the command-line arguments
*/
/*public static void main(String[] args) {
int source = 0;
int destination = 1;
int vertex = 5;
EdgeWeightedDigraph G = new EdgeWeightedDigraph(vertex);//create duplex edges upon initiation
G.addEdge(new DirectedEdge(0,2,"optical",10,10000));
G.addEdge(new DirectedEdge(2,0,"optical",10,10000));
G.addEdge(new DirectedEdge(0,3,"optical",10,10000));
G.addEdge(new DirectedEdge(3,0,"optical",10,10000));
G.addEdge(new DirectedEdge(1,2,"optical",10,10000));
G.addEdge(new DirectedEdge(2,1,"optical",10,10000));
G.addEdge(new DirectedEdge(1,3,"optical",10,10000));
G.addEdge(new DirectedEdge(3,1,"optical",10,10000));
G.addEdge(new DirectedEdge(0,4,"copper",8,100));
G.addEdge(new DirectedEdge(4,0,"copper",8,100));
G.addEdge(new DirectedEdge(1,4,"copper",8,100));
G.addEdge(new DirectedEdge(2,4,"copper",8,100));
G.addEdge(new DirectedEdge(4,2,"copper",8,100));
G.addEdge(new DirectedEdge(4,1,"copper",8,100));
G.addEdge(new DirectedEdge(3,4,"copper",8,100));
G.addEdge(new DirectedEdge(4,3,"copper",8,100));
// compute shortest paths
DijkstraSP sp = new DijkstraSP(G, source);// edit this to have 2 parameters, source and destination
*/
// print shortest path
/*
for (int t = 0; t < G.V(); t++) {
if (sp.hasPathTo(t)) {
StdOut.printf("%d to %d (%.2f) ", source, t, sp.distTo(t));
for (DirectedEdge e : sp.pathTo(t)) {
StdOut.print(e + " ");
}
StdOut.println();
}
else {
StdOut.printf("%d to %d no path\n", source, t);
}
}*/
//ArrayList<DirectedEdge> results = sp.pathTo(destination);
// StdOut.printf("%d to %d (%.2f) ", source, destination, sp.distTo(destination));
//for(int i = results.size()-1;i>=0;i--)
//{
//System.out.println(results.get(i));
//}
//System.out.println(G.isCopperOnly());
// System.out.println(sp.bandwidth(results));
//}
}