-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph.java
executable file
·473 lines (407 loc) · 13.8 KB
/
Graph.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
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
import weiss.util.Iterator;
import weiss.util.Collection;
import weiss.util.List;
import weiss.util.Queue;
import weiss.util.Map;
import weiss.util.LinkedList;
import weiss.util.HashMap;
import weiss.util.NoSuchElementException;
import weiss.util.PriorityQueue;
import weiss.nonstandard.PairingHeap;
// Used to signal violations of preconditions for
// various shortest path algorithms.
class GraphException extends RuntimeException
{
public GraphException( String name )
{
super( name );
}
}
// Represents an edge in the graph.
class Edge
{
public Vertex dest; // Second vertex in Edge
public double cost; // Edge cost
public Edge( Vertex d, double c )
{
dest = d;
cost = c;
}
}
// Represents an entry in the priority queue for Dijkstra's algorithm.
class Path implements Comparable<Path>
{
public Vertex dest; // w
public double cost; // d(w)
public Path( Vertex d, double c )
{
dest = d;
cost = c;
}
public int compareTo( Path rhs )
{
double otherCost = rhs.cost;
return cost < otherCost ? -1 : cost > otherCost ? 1 : 0;
}
}
// Represents a vertex in the graph.
class Vertex
{
public String name; // Vertex name
public List<Edge> adj; // Adjacent vertices
public double dist; // Cost
public Vertex prev; // Previous vertex on shortest path
public int scratch;// Extra variable used in algorithm
public Vertex( String nm )
{ name = nm; adj = new LinkedList<Edge>( ); reset( ); }
public void reset( )
{ dist = Graph.INFINITY; prev = null; pos = null; scratch = 0; }
public PairingHeap.Position<Path> pos; // Used for dijkstra2 (Chapter 23)
}
// Graph class: evaluate shortest paths.
//
// CONSTRUCTION: with no parameters.
//
// ******************PUBLIC OPERATIONS**********************
// void addEdge( String v, String w, double cvw )
// --> Add additional edge
// void printPath( String w ) --> Print path after alg is run
// void unweighted( String s ) --> Single-source unweighted
// void dijkstra( String s ) --> Single-source weighted
// void negative( String s ) --> Single-source negative weighted
// void acyclic( String s ) --> Single-source acyclic
// ******************ERRORS*********************************
// Some error checking is performed to make sure graph is ok,
// and to make sure graph satisfies properties needed by each
// algorithm. Exceptions are thrown if errors are detected.
public class Graph
{
public static final double INFINITY = Double.MAX_VALUE;
private Map<String,Vertex> vertexMap = new HashMap<String,Vertex>( );
/**
* Add a new edge to the graph.
*/
public void addEdge( String sourceName, String destName, double cost )
{
Vertex v = getVertex( sourceName );
Vertex w = getVertex( destName );
v.adj.add( new Edge( w, cost ) );
}
/**
* Driver routine to handle unreachables and print total cost.
* It calls recursive routine to print shortest path to
* destNode after a shortest path algorithm has run.
*/
public void printPath( String destName )
{
Vertex w = vertexMap.get( destName );
if( w == null )
throw new NoSuchElementException( "Destination vertex not found" );
else if( w.dist == INFINITY )
System.out.println( destName + " is unreachable" );
else
{
System.out.print( "(Cost is: " + w.dist + ") " );
printPath( w );
System.out.println( );
}
}
/**
* If vertexName is not present, add it to vertexMap.
* In either case, return the Vertex.
*/
private Vertex getVertex( String vertexName )
{
Vertex v = vertexMap.get( vertexName );
if( v == null )
{
v = new Vertex( vertexName );
vertexMap.put( vertexName, v );
}
return v;
}
/**
* Recursive routine to print shortest path to dest
* after running shortest path algorithm. The path
* is known to exist.
*/
private void printPath( Vertex dest )
{
if( dest.prev != null )
{
printPath( dest.prev );
System.out.print( " to " );
}
System.out.print( dest.name );
}
/**
* Initializes the vertex output info prior to running
* any shortest path algorithm.
*/
private void clearAll( )
{
for( Vertex v : vertexMap.values( ) )
v.reset( );
}
/**
* Single-source unweighted shortest-path algorithm.
*/
public void unweighted( String startName )
{
clearAll( );
Vertex start = vertexMap.get( startName );
if( start == null )
throw new NoSuchElementException( "Start vertex not found" );
Queue<Vertex> q = new LinkedList<Vertex>( );
q.add( start ); start.dist = 0;
while( !q.isEmpty( ) )
{
Vertex v = q.remove( );
for( Edge e : v.adj )
{
Vertex w = e.dest;
if( w.dist == INFINITY )
{
w.dist = v.dist + 1;
w.prev = v;
q.add( w );
}
}
}
}
/**
* Single-source weighted shortest-path algorithm.
*/
public void dijkstra( String startName )
{
PriorityQueue<Path> pq = new PriorityQueue<Path>( );
Vertex start = vertexMap.get( startName );
if( start == null )
throw new NoSuchElementException( "Start vertex not found" );
clearAll( );
pq.add( new Path( start, 0 ) ); start.dist = 0;
int nodesSeen = 0;
while( !pq.isEmpty( ) && nodesSeen < vertexMap.size( ) )
{
Path vrec = pq.remove( );
Vertex v = vrec.dest;
if( v.scratch != 0 ) // already processed v
continue;
v.scratch = 1;
nodesSeen++;
for( Edge e : v.adj )
{
Vertex w = e.dest;
double cvw = e.cost;
if( cvw < 0 )
throw new GraphException( "Graph has negative edges" );
if( w.dist > v.dist + cvw )
{
w.dist = v.dist +cvw;
w.prev = v;
pq.add( new Path( w, w.dist ) );
}
}
}
}
/**
* Single-source weighted shortest-path algorithm using pairing heaps.
*/
public void dijkstra2( String startName )
{
PairingHeap<Path> pq = new PairingHeap<Path>( );
Vertex start = vertexMap.get( startName );
if( start == null )
throw new NoSuchElementException( "Start vertex not found" );
clearAll( );
start.pos = pq.insert( new Path( start, 0 ) ); start.dist = 0;
while ( !pq.isEmpty( ) )
{
Path vrec = pq.deleteMin( );
Vertex v = vrec.dest;
for( Edge e : v.adj )
{
Vertex w = e.dest;
double cvw = e.cost;
if( cvw < 0 )
throw new GraphException( "Graph has negative edges" );
if( w.dist > v.dist + cvw )
{
w.dist = v.dist + cvw;
w.prev = v;
Path newVal = new Path( w, w.dist );
if( w.pos == null )
w.pos = pq.insert( newVal );
else
pq.decreaseKey( w.pos, newVal );
}
}
}
}
/**
* Single-source negative-weighted shortest-path algorithm.
*/
public void negative( String startName )
{
clearAll( );
Vertex start = vertexMap.get( startName );
if( start == null )
throw new NoSuchElementException( "Start vertex not found" );
Queue<Vertex> q = new LinkedList<Vertex>( );
q.add( start ); start.dist = 0; start.scratch++;
while( !q.isEmpty( ) )
{
Vertex v = q.remove( );
if( v.scratch++ > 2 * vertexMap.size( ) )
throw new GraphException( "Negative cycle detected" );
for( Edge e : v.adj )
{
Vertex w = e.dest;
double cvw = e.cost;
if( w.dist > v.dist + cvw )
{
w.dist = v.dist + cvw;
w.prev = v;
// Enqueue only if not already on the queue
if( w.scratch++ % 2 == 0 )
q.add( w );
else
w.scratch--; // undo the enqueue increment
}
}
}
}
/**
* Single-source negative-weighted acyclic-graph shortest-path algorithm.
*/
public void acyclic( String startName )
{
Vertex start = vertexMap.get( startName );
if( start == null )
throw new NoSuchElementException( "Start vertex not found" );
clearAll( );
Queue<Vertex> q = new LinkedList<Vertex>( );
start.dist = 0;
// Compute the indegrees
Collection<Vertex> vertexSet = vertexMap.values( );
for( Vertex v : vertexSet )
for( Edge e : v.adj )
e.dest.scratch++;
// Enqueue vertices of indegree zero
for( Vertex v : vertexSet )
if( v.scratch == 0 )
q.add( v );
int iterations;
for( iterations = 0; !q.isEmpty( ); iterations++ )
{
Vertex v = q.remove( );
for( Edge e : v.adj )
{
Vertex w = e.dest;
double cvw = e.cost;
if( --w.scratch == 0 )
q.add( w );
if( v.dist == INFINITY )
continue;
if( w.dist > v.dist + cvw )
{
w.dist = v.dist + cvw;
w.prev = v;
}
}
}
if( iterations != vertexMap.size( ) )
throw new GraphException( "Graph has a cycle!" );
}
/**
* Process a request; return false if end of file.
*/
public static boolean processRequest( BufferedReader in, Graph g )
{
String startName = null;
String destName = null;
String alg = null;
try
{
System.out.print( "Enter start node:" );
if( ( startName = in.readLine( ) ) == null )
return false;
System.out.print( "Enter destination node:" );
if( ( destName = in.readLine( ) ) == null )
return false;
System.out.print( " Enter algorithm (u, d, n, a ): " );
if( ( alg = in.readLine( ) ) == null )
return false;
if( alg.equals( "u" ) )
g.unweighted( startName );
else if( alg.equals( "d" ) )
{
g.dijkstra( startName );
g.printPath( destName );
g.dijkstra2( startName );
}
else if( alg.equals( "n" ) )
g.negative( startName );
else if( alg.equals( "a" ) )
g.acyclic( startName );
g.printPath( destName );
}
catch( IOException e )
{ System.err.println( e ); }
catch( NoSuchElementException e )
{ System.err.println( e ); }
catch( GraphException e )
{ System.err.println( e ); }
return true;
}
/**
* A main routine that:
* 1. Reads a file containing edges (supplied as a command-line parameter);
* 2. Forms the graph;
* 3. Repeatedly prompts for two vertices and
* runs the shortest path algorithm.
* The data file is a sequence of lines of the format
* source destination.
*/
public static void main( String [ ] args )
{
Graph g = new Graph( );
try
{
FileReader fin = new FileReader( args[0] );
BufferedReader graphFile = new BufferedReader( fin );
// Read the edges and insert
String line;
while( ( line = graphFile.readLine( ) ) != null )
{
StringTokenizer st = new StringTokenizer( line );
try
{
if( st.countTokens( ) != 3 )
{
System.err.println( "Skipping ill-formatted line " + line );
continue;
}
String source = st.nextToken( );
String dest = st.nextToken( );
int cost = Integer.parseInt( st.nextToken( ) );
g.addEdge( source, dest, cost );
}
catch( NumberFormatException e )
{ System.err.println( "Skipping ill-formatted line " + line ); }
}
}
catch( IOException e )
{ System.err.println( e ); }
System.out.println( "File read..." );
System.out.println( g.vertexMap.size( ) + " vertices" );
BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
while( processRequest( in, g ) )
;
}
}