-
Notifications
You must be signed in to change notification settings - Fork 1
/
Graph.java
637 lines (580 loc) · 16.3 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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/*
* STUDENT ID:801027386
* STUDENT NAME: ARUN KUNNUMPURAM THOMAS
* FILE NAME: Graph.java
*
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Graph
{
/*
* it contains a vertices hashmap which holds the name of vertex and vertex object.
*/
private HashMap<String,Vertex> vertices= new HashMap<String,Vertex>();
/*
* This method is used to add edges in both direction. If there is a duplicate edge ,then
* it will update the current cost
*/
public void addEdgeFromInputFile(String vertex1, String vertex2, double cost)
{
// checking vertex1 is existing in graph
Vertex v1=getVertex(vertex1);
// checking vertex1 is existing in graph
Vertex v2=getVertex(vertex2);
Edge v1ToV2= new Edge();
v1ToV2.setSourceVertex(vertex1);
v1ToV2.setDestVertex(vertex2);
v1ToV2.setCost(cost);
ArrayList<Edge> v1OutwaredEdges= v1.getOutwardEdges();
if(v1OutwaredEdges.size() ==0)
{
v1.outwardEdges.add(v1ToV2);
}
else
{
if(v1.outwardEdges.contains(v1ToV2))
{
System.out.println("Duplicate Edge... Updating the cost !!!!");
v1.outwardEdges.set(v1.outwardEdges.indexOf(v1ToV2), v1ToV2);
}
else
{
v1.outwardEdges.add(v1ToV2);
}
}
Edge v2ToV1= new Edge();
v2ToV1.setSourceVertex(vertex2);
v2ToV1.setDestVertex(vertex1);
v2ToV1.setCost(cost);
ArrayList<Edge> v2OutwaredEdges= v2.getOutwardEdges();
if(v2OutwaredEdges.size() ==0)
{
v2.outwardEdges.add(v2ToV1);
}
else
{
if(v2.outwardEdges.contains(v2ToV1))
{
System.out.println("Duplicate Edge... Updating the cost !!!!");
v2.outwardEdges.set(v2.outwardEdges.indexOf(v2ToV1), v2ToV1);
}
else
{
v2.outwardEdges.add(v2ToV1);
}
}
}
/*
* This method is using to get the vertex from hashmap which is having the vertex details of the graph
* if there is no vertex present in the hashmap, it will create new one and put it in hashmap
* reference: quiz 8 file
*/
private Vertex getVertex( String vertexName )
{
Vertex v = vertices.get( vertexName );
if( v == null )
{
v = new Vertex( vertexName );
vertices.put( vertexName, v );
}
return v;
}
/*
* This method is used to build the graph from input file
* reference: quiz 8 file
*/
public void buildGraph(String network)
{
try
{
FileReader fin = new FileReader(network);
Scanner graphFile = new Scanner( fin );
// Read the edges and insert
String line;
while( graphFile.hasNextLine( ) )
{
line = graphFile.nextLine( );
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( );
double cost = Double.parseDouble(st.nextToken());
// System.out.println(source +" "+ dest+" "+cost);
// g.addEdge( source, dest );
addEdgeFromInputFile(source,dest,cost);
}
catch( NumberFormatException e )
{ System.err.println( "Skipping ill-formatted line " + line ); }
}
}
catch( IOException e )
{ System.err.println( e ); }
}
/*
* This method is used to adding an edge from tail vertex to head vertex
* if edge is already present it will update the cost
* if the vertex is not present then it will use getVertex method to create one
*/
public void addedge(String dest, String source,double cost)
{
Vertex vertex=getVertex(source);
Vertex destVertex=getVertex(dest);
Edge edge= new Edge();
edge.setSourceVertex(source);
edge.setDestVertex(dest);
edge.setCost(cost);
ArrayList<Edge> outwardEdges= vertex.getOutwardEdges();
if(outwardEdges.size() ==0)
{
vertex.outwardEdges.add(edge);
}
else
{
if(vertex.outwardEdges.contains(edge))
{
int index=vertex.outwardEdges.indexOf(edge);
System.out.println("Duplicate Edge... Source: "+ edge.sourceVertex +" Dest: "+edge.destVertex +" Updating the cost !!!!");
edge.status=vertex.outwardEdges.get(index).status;
vertex.outwardEdges.set(index, edge);
}
else
{
vertex.outwardEdges.add(edge);
}
}
}
/*This method is used to delete an edge from tail vertex to head vertex
*
*/
public void deletedge(String dest, String source)
{
if(vertices.containsKey(source) && vertices.containsKey(dest))
{
Vertex vertex= vertices.get(source);
Edge edge= new Edge();
edge.setSourceVertex(source);
edge.setDestVertex(dest);
if(vertex.outwardEdges.contains(edge))
{
// System.out.println("Deleting edge... Source: "+ edge.sourceVertex +" Dest: "+edge.destVertex);
vertex.outwardEdges.remove(vertex.outwardEdges.indexOf(edge));
}
}
else
{
System.out.println("Error !!! There is no source|destination vertex ");
}
}
/*
* This method is used to mark an edge down
* It will make the status of edge to false
*/
public void edgedown(String dest, String source)
{
if(vertices.containsKey(source) && vertices.containsKey(dest))
{
Vertex vertex= vertices.get(source);
Edge edge= new Edge();
edge.setSourceVertex(source);
edge.setDestVertex(dest);
edge.status=false;
if(vertex.outwardEdges.contains(edge))
{
int index=vertex.outwardEdges.indexOf(edge);
edge.cost=vertex.outwardEdges.get(index).cost;
// System.out.println("making Edge down... Source: "+ edge.sourceVertex +" Dest: "+edge.destVertex);
vertex.outwardEdges.set(vertex.outwardEdges.indexOf(edge), edge);
}
}
else
{
System.out.println("Error !!! There is no source|dest vertex with name ");
}
}
/*
* This method is used to mark an edge up
* It will make the status of edge to true
*/
public void edgeup(String dest, String source)
{
if(vertices.containsKey(source) && vertices.containsKey(dest))
{
Vertex vertex= vertices.get(source);
Edge edge= new Edge();
edge.setSourceVertex(source);
edge.setDestVertex(dest);
edge.status=true;
if(vertex.outwardEdges.contains(edge))
{
int index=vertex.outwardEdges.indexOf(edge);
edge.cost=vertex.outwardEdges.get(index).cost;
// System.out.println("making Edge up... Source: "+ edge.sourceVertex +" Dest: "+edge.destVertex);
vertex.outwardEdges.set(vertex.outwardEdges.indexOf(edge), edge);
}
}
else
{
System.out.println("Error !!! There is no source|dest vertex with name ");
}
}
/*
* This method is used to mark a vertex down
* It will make the status of vertex to false
*/
public void vertexdown(String vertex)
{
if(vertices.containsKey(vertex))
{
Vertex vertexToDown= vertices.get(vertex);
// System.out.println("making Vertex down... Vertex: "+ vertexToDown.vertexName);
vertexToDown.status=false;
}
else
{
System.out.println("Error !!! There is no source vertex with name "+vertex);
}
}
/*
* This method is used to mark a vertex up
* It will make the status of vertex to true
*/
public void vertexup(String vertex)
{
if(vertices.containsKey(vertex))
{
Vertex vertexToDown= vertices.get(vertex);
// System.out.println("making Vertex up... Vertex: "+ vertexToDown.vertexName);
vertexToDown.status=true;
}
else
{
System.out.println("Error !!! There is no source vertex with name "+vertex);
}
}
/*
* This method is used to print the graph- vertex in alphabetical order and its edges in
* alphabetical order
*/
public String print()
{
StringBuilder sb= new StringBuilder();
HashMap<String,Vertex> hm1= vertices;
ArrayList<Vertex> vertexList= new ArrayList<Vertex>();
for (Map.Entry<String, Vertex> entry : hm1.entrySet())
vertexList.add(entry.getValue());
Collections.sort(vertexList,Vertex.vertexNameCompartor);
for(Vertex vertex : vertexList)
{
// System.out.println("---------------------------------------------");
if(!vertex.status)
{
//System.out.println(vertex.getVertexName()+ " DOWN");
sb.append(vertex.getVertexName()+ " DOWN \n");
}
else
{
//System.out.println(vertex.getVertexName());
sb.append(vertex.getVertexName()+ "\n");
}
//System.out.println("Edges!!!!!!!!!!!!");
for(Edge e : vertex.getOutwardEdges())
{
if(!e.status)
{
//System.out.println(" "+e.getDestVertex()+ " "+e.getCost() + " DOWN");
sb.append(" "+e.getDestVertex()+ " "+e.getCost() + " DOWN \n");
}
else
{
//System.out.println(" "+e.getDestVertex() +" "+e.getCost());
sb.append(" "+e.getDestVertex()+ " "+e.getCost() + "\n");
}
}
// System.out.println("---------------------------------------------");
// ...
}
System.out.println(sb.toString());
return sb.toString();
}
/*
* This method is find the shortest path from given source and destination veretx.
* This is implemented using Dijisktra algorithm and I am using min binary heap(Heap.java) for implementing min priority queue
*
*/
public String shortestpath(String source,String dest)
{
boolean isDestFound=false;
int count=0;
HashMap<String,Vertex> hm1= vertices;
//finding number of vertex
for (Map.Entry<String, Vertex> entry : hm1.entrySet())
{
count++;
}
//declaring based on number of vertex
double[] cost = new double[count];
String[] vertex = new String[count];
int noOfVertex=count;
//initializing the distance to MAX
int i=0;
for (Map.Entry<String, Vertex> entry : hm1.entrySet())
{
vertex[i]=entry.getKey();
entry.getValue().distance=Double.MAX_VALUE;
cost[i]=Double.MAX_VALUE;
i++;
}
int sourceIndex=Arrays.asList(vertex).indexOf(source);
if(sourceIndex<0)
return "Source vertex "+ source +" not found for the path \n";
if(vertices.get(dest) ==null)
return "Destination vertex "+ dest +" not found \n";
vertices.get(source).distance=0.0;
vertices.get(source).predecessor=null;
cost[sourceIndex]=0.0;
Heap heap= new Heap(cost, vertex, noOfVertex);
//heap.decreseKey("Education",3.0);
// System.out.println("current min"+heap.extractMin());
ArrayList<String> completedVertices= new ArrayList<String>();
completedVertices.add(source);
while(noOfVertex>0)
{
String min=heap.extractMin();
Vertex minVertex= vertices.get(min);
completedVertices.add(min);
if(minVertex.status)
{
ArrayList<Edge> edges=minVertex.getOutwardEdges();
Edge [] edgesArray = edges.toArray(new Edge[edges.size()]);
Iterator it= edges.iterator();
for(int k=0;k<edgesArray.length;k++)
{
Edge edge=edgesArray[k];
if(!(completedVertices.contains(edge.destVertex)) && vertices.get(edge.destVertex).distance>(minVertex.distance+edge.cost)&& edge.status)
{
String destVertexName=edge.destVertex;
if(destVertexName.equals(dest))
isDestFound=true;
double newDist=minVertex.distance+edge.cost;;
vertices.get(destVertexName).distance= newDist;
vertices.get(destVertexName).predecessor=minVertex;
heap.decreseKey(edge.destVertex, newDist);
}
}
}
noOfVertex--;
}
Vertex destinationVertex=vertices.get(dest);
Vertex predecessor=destinationVertex.predecessor;
StringBuilder path= new StringBuilder();
BigDecimal bd = new BigDecimal(Double.toString(destinationVertex.distance));
bd = bd.setScale(2, RoundingMode.HALF_UP);
path.append(bd.doubleValue() + " ");
path.append(destinationVertex.getVertexName()+" ");
while(predecessor !=null)
{
path.append(predecessor.getVertexName());
path.append(" ");
predecessor=predecessor.predecessor;
}
String[] arr = path.toString().split(" ");
StringBuilder sb = new StringBuilder();
for (int z = arr.length - 1; z >= 0; --z) {
if (!arr[z].equals("")) {
sb.append(arr[z]).append(" ");
}
}
sb.append("\n");
System.out.println(sb.toString());
if(!isDestFound)
return "Path not found from "+source+ " to "+ dest+"\n";
return sb.toString();
}
/*
* this method is used to find the reachable vertex from each vertex.
* This is implemented using BFS algorithm.
*/
public String reachable()
{
StringBuilder sb= new StringBuilder();
int count=0;
HashMap<String,Vertex> hm1= vertices;
//finding number of vertex
for (Map.Entry<String, Vertex> entry : hm1.entrySet())
{
count++;
}
String[] vertex = new String[count];
int noOfVertex=count;
int i=0;
for (Map.Entry<String, Vertex> entry : hm1.entrySet())
{
vertex[i]=entry.getKey();
i++;
}
Arrays.sort(vertex);
for(int j=0;j<vertex.length;j++)
{
ArrayList<String> completedVertices= new ArrayList<String>();
completedVertices.add(vertex[j]);
if(!vertices.get(vertex[j]).status)
{
continue;
}
sb.append(vertex[j]+"\n");
Queue<String> myQueue = new LinkedList<String>();
ArrayList<String> reachableVertex= new ArrayList<String>();
myQueue.add(vertex[j]);
while(!myQueue.isEmpty())
{
Vertex sourceVertex= vertices.get(myQueue.poll());
if(sourceVertex.status)
{
ArrayList<Edge> edges=sourceVertex.getOutwardEdges();
Edge [] edgesArray = edges.toArray(new Edge[edges.size()]);
Arrays.sort(edgesArray,Edge.edgeNameCompartor);
for(int k=0;k<edges.size();k++)
{
Edge edge=edgesArray[k];
if(!(completedVertices.contains(edge.destVertex)) && edge.status)
{
if(vertices.get(edge.destVertex).status)
{
reachableVertex.add(" "+edge.destVertex+"\n");
myQueue.add(edge.destVertex);
}
completedVertices.add(edge.destVertex);
}
}
}
}
Collections.sort(reachableVertex);
for(String x : reachableVertex)
{
sb.append(x);
}
}
System.out.println(sb.toString());
return sb.toString();
}
/*
* this method is used to execute the queries in the given input file and writing the output to given
* output file
*/
public void executeQuery(String queryFileName, String outputFileName)
{
try
{
FileReader fin = new FileReader(queryFileName);
Scanner graphFile = new Scanner( fin );
FileWriter fw= new FileWriter(outputFileName);
BufferedWriter bw = new BufferedWriter(fw);
// Read the edges and insert
String line;
while( graphFile.hasNextLine( ) )
{
line = graphFile.nextLine( );
StringTokenizer st = new StringTokenizer( line );
try
{
String operation = st.nextToken( );
String dest;
String source;
double cost;
switch (operation) {
case "print":
String printOutPut=print();
bw.write(printOutPut);
bw.write("\n");
break;
case "path":
source=st.nextToken( );
dest=st.nextToken( );
String pathOutput=shortestpath(source, dest);
bw.write(pathOutput);
bw.write("\n");
break;
case "reachable":
String reachOutput=reachable();
bw.write(reachOutput);
bw.write("\n");
break;
case "edgeup":
source=st.nextToken( );
dest=st.nextToken( );
edgeup(dest,source);
break;
case "edgedown":
source=st.nextToken( );
dest=st.nextToken( );
edgedown(dest,source);
break;
case "vertexup":
String vertexToUp=st.nextToken( );
vertexup(vertexToUp);
break;
case "vertexdown":
String vertexToDown=st.nextToken( );
vertexdown(vertexToDown);
break;
case "deleteedge":
source=st.nextToken( );
dest=st.nextToken( );
deletedge(dest, source);
break;
case "addedge":
source=st.nextToken( );
dest=st.nextToken( );
cost=Double.parseDouble(st.nextToken( ));
addedge(dest,source,cost);
break;
case "quit":
bw.close();
System.exit(0);
default:
break;
}
}
catch( NumberFormatException e )
{ System.err.println( "Skipping ill-formatted line " + line ); }
}
bw.close();
}
catch( IOException e )
{ System.err.println( e ); }
}
public static void main(String[] args)
{
// TODO Auto-generated method stub
if(args.length !=3)
{
System.out.println("Please pass all inputs <network,queries,outputfilename>");
System.exit(0);
}
Graph g = new Graph();
g.buildGraph(args[0]);
g.executeQuery(args[1],args[2]);
}
}