-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph_M.java
704 lines (609 loc) · 20.4 KB
/
Graph_M.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
import java.util.*;
import java.io.*;
public class Graph_M
{
public class Vertex
{
HashMap<String, Integer> nbrs = new HashMap<>();
}
static HashMap<String, Vertex> vtces;
public Graph_M()
{
vtces = new HashMap<>();
}
public int numVetex()
{
return this.vtces.size();
}
public boolean containsVertex(String vname)
{
return this.vtces.containsKey(vname);
}
public void addVertex(String vname)
{
Vertex vtx = new Vertex();
vtces.put(vname, vtx);
}
public void removeVertex(String vname)
{
Vertex vtx = vtces.get(vname);
ArrayList<String> keys = new ArrayList<>(vtx.nbrs.keySet());
for (String key : keys)
{
Vertex nbrVtx = vtces.get(key);
nbrVtx.nbrs.remove(vname);
}
vtces.remove(vname);
}
public int numEdges()
{
ArrayList<String> keys = new ArrayList<>(vtces.keySet());
int count = 0;
for (String key : keys)
{
Vertex vtx = vtces.get(key);
count = count + vtx.nbrs.size();
}
return count / 2;
}
public boolean containsEdge(String vname1, String vname2)
{
Vertex vtx1 = vtces.get(vname1);
Vertex vtx2 = vtces.get(vname2);
if (vtx1 == null || vtx2 == null || !vtx1.nbrs.containsKey(vname2)) {
return false;
}
return true;
}
public void addEdge(String vname1, String vname2, int value)
{
Vertex vtx1 = vtces.get(vname1);
Vertex vtx2 = vtces.get(vname2);
if (vtx1 == null || vtx2 == null || vtx1.nbrs.containsKey(vname2)) {
return;
}
vtx1.nbrs.put(vname2, value);
vtx2.nbrs.put(vname1, value);
}
public void removeEdge(String vname1, String vname2)
{
Vertex vtx1 = vtces.get(vname1);
Vertex vtx2 = vtces.get(vname2);
//check if the vertices given or the edge between these vertices exist or not
if (vtx1 == null || vtx2 == null || !vtx1.nbrs.containsKey(vname2)) {
return;
}
vtx1.nbrs.remove(vname2);
vtx2.nbrs.remove(vname1);
}
public void display_Map()
{
System.out.println("\t Delhi Metro Map");
System.out.println("\t------------------");
System.out.println("----------------------------------------------------\n");
ArrayList<String> keys = new ArrayList<>(vtces.keySet());
for (String key : keys)
{
String str = key + " =>\n";
Vertex vtx = vtces.get(key);
ArrayList<String> vtxnbrs = new ArrayList<>(vtx.nbrs.keySet());
for (String nbr : vtxnbrs)
{
str = str + "\t" + nbr + "\t";
if (nbr.length()<16)
str = str + "\t";
if (nbr.length()<8)
str = str + "\t";
str = str + vtx.nbrs.get(nbr) + "\n";
}
System.out.println(str);
}
System.out.println("\t------------------");
System.out.println("---------------------------------------------------\n");
}
public void display_Stations()
{
System.out.println("\n***********************************************************************\n");
ArrayList<String> keys = new ArrayList<>(vtces.keySet());
int i=1;
for(String key : keys)
{
System.out.println(i + ". " + key);
i++;
}
System.out.println("\n***********************************************************************\n");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
public boolean hasPath(String vname1, String vname2, HashMap<String, Boolean> processed)
{
// DIR EDGE
if (containsEdge(vname1, vname2)) {
return true;
}
//MARK AS DONE
processed.put(vname1, true);
Vertex vtx = vtces.get(vname1);
ArrayList<String> nbrs = new ArrayList<>(vtx.nbrs.keySet());
//TRAVERSE THE NBRS OF THE VERTEX
for (String nbr : nbrs)
{
if (!processed.containsKey(nbr))
if (hasPath(nbr, vname2, processed))
return true;
}
return false;
}
private class DijkstraPair implements Comparable<DijkstraPair>
{
String vname;
String psf;
int cost;
/*
The compareTo method is defined in Java.lang.Comparable.
Here, we override the method because the conventional compareTo method
is used to compare strings,integers and other primitive data types. But
here in this case, we intend to compare two objects of DijkstraPair class.
*/
/*
Removing the overriden method gives us this errror:
The type Graph_M.DijkstraPair must implement the inherited abstract method Comparable<Graph_M.DijkstraPair>.compareTo(Graph_M.DijkstraPair)
This is because DijkstraPair is not an abstract class and implements Comparable interface which has an abstract
method compareTo. In order to make our class concrete(a class which provides implementation for all its methods)
we have to override the method compareTo
*/
@Override
public int compareTo(DijkstraPair o)
{
return o.cost - this.cost;
}
}
public int dijkstra(String src, String des, boolean nan)
{
int val = 0;
ArrayList<String> ans = new ArrayList<>();
HashMap<String, DijkstraPair> map = new HashMap<>();
Heap<DijkstraPair> heap = new Heap<>();
for (String key : vtces.keySet())
{
DijkstraPair np = new DijkstraPair();
np.vname = key;
//np.psf = "";
np.cost = Integer.MAX_VALUE;
if (key.equals(src))
{
np.cost = 0;
np.psf = key;
}
heap.add(np);
map.put(key, np);
}
//keep removing the pairs while heap is not empty
while (!heap.isEmpty())
{
DijkstraPair rp = heap.remove();
if(rp.vname.equals(des))
{
val = rp.cost;
break;
}
map.remove(rp.vname);
ans.add(rp.vname);
Vertex v = vtces.get(rp.vname);
for (String nbr : v.nbrs.keySet())
{
if (map.containsKey(nbr))
{
int oc = map.get(nbr).cost;
Vertex k = vtces.get(rp.vname);
int nc;
if(nan)
nc = rp.cost + 120 + 40*k.nbrs.get(nbr);
else
nc = rp.cost + k.nbrs.get(nbr);
if (nc < oc)
{
DijkstraPair gp = map.get(nbr);
gp.psf = rp.psf + nbr;
gp.cost = nc;
heap.updatePriority(gp);
}
}
}
}
return val;
}
private class Pair
{
String vname;
String psf;
int min_dis;
int min_time;
}
public String Get_Minimum_Distance(String src, String dst)
{
int min = Integer.MAX_VALUE;
//int time = 0;
String ans = "";
HashMap<String, Boolean> processed = new HashMap<>();
LinkedList<Pair> stack = new LinkedList<>();
// create a new pair
Pair sp = new Pair();
sp.vname = src;
sp.psf = src + " ";
sp.min_dis = 0;
sp.min_time = 0;
// put the new pair in stack
stack.addFirst(sp);
// while stack is not empty keep on doing the work
while (!stack.isEmpty())
{
// remove a pair from stack
Pair rp = stack.removeFirst();
if (processed.containsKey(rp.vname))
{
continue;
}
// processed put
processed.put(rp.vname, true);
//if there exists a direct edge b/w removed pair and destination vertex
if (rp.vname.equals(dst))
{
int temp = rp.min_dis;
if(temp<min) {
ans = rp.psf;
min = temp;
}
continue;
}
Vertex rpvtx = vtces.get(rp.vname);
ArrayList<String> nbrs = new ArrayList<>(rpvtx.nbrs.keySet());
for(String nbr : nbrs)
{
// process only unprocessed nbrs
if (!processed.containsKey(nbr)) {
// make a new pair of nbr and put in queue
Pair np = new Pair();
np.vname = nbr;
np.psf = rp.psf + nbr + " ";
np.min_dis = rp.min_dis + rpvtx.nbrs.get(nbr);
//np.min_time = rp.min_time + 120 + 40*rpvtx.nbrs.get(nbr);
stack.addFirst(np);
}
}
}
ans = ans + Integer.toString(min);
return ans;
}
public String Get_Minimum_Time(String src, String dst)
{
int min = Integer.MAX_VALUE;
String ans = "";
HashMap<String, Boolean> processed = new HashMap<>();
LinkedList<Pair> stack = new LinkedList<>();
// create a new pair
Pair sp = new Pair();
sp.vname = src;
sp.psf = src + " ";
sp.min_dis = 0;
sp.min_time = 0;
// put the new pair in queue
stack.addFirst(sp);
// while queue is not empty keep on doing the work
while (!stack.isEmpty()) {
// remove a pair from queue
Pair rp = stack.removeFirst();
if (processed.containsKey(rp.vname))
{
continue;
}
// processed put
processed.put(rp.vname, true);
//if there exists a direct edge b/w removed pair and destination vertex
if (rp.vname.equals(dst))
{
int temp = rp.min_time;
if(temp<min) {
ans = rp.psf;
min = temp;
}
continue;
}
Vertex rpvtx = vtces.get(rp.vname);
ArrayList<String> nbrs = new ArrayList<>(rpvtx.nbrs.keySet());
for (String nbr : nbrs)
{
// process only unprocessed nbrs
if (!processed.containsKey(nbr)) {
// make a new pair of nbr and put in queue
Pair np = new Pair();
np.vname = nbr;
np.psf = rp.psf + nbr + " ";
//np.min_dis = rp.min_dis + rpvtx.nbrs.get(nbr);
np.min_time = rp.min_time + 120 + 40*rpvtx.nbrs.get(nbr);
stack.addFirst(np);
}
}
}
Double minutes = Math.ceil((double)min / 60);
ans = ans + Double.toString(minutes);
return ans;
}
public ArrayList<String> get_Interchanges(String str)
{
ArrayList<String> arr = new ArrayList<>();
String res[] = str.split(" ");
arr.add(res[0]);
int count = 0;
for(int i=1;i<res.length-1;i++)
{
int index = res[i].indexOf('~');
String s = res[i].substring(index+1);
if(s.length()==2)
{
String prev = res[i-1].substring(res[i-1].indexOf('~')+1);
String next = res[i+1].substring(res[i+1].indexOf('~')+1);
if(prev.equals(next))
{
arr.add(res[i]);
}
else
{
arr.add(res[i]+" ==> "+res[i+1]);
i++;
count++;
}
}
else
{
arr.add(res[i]);
}
}
arr.add(Integer.toString(count));
arr.add(res[res.length-1]);
return arr;
}
public static void Create_Metro_Map(Graph_M g)
{
g.addVertex("Noida Sector 62~B");
g.addVertex("Botanical Garden~B");
g.addVertex("Yamuna Bank~B");
g.addVertex("Rajiv Chowk~BY");
g.addVertex("Vaishali~B");
g.addVertex("Moti Nagar~B");
g.addVertex("Janak Puri West~BO");
g.addVertex("Dwarka Sector 21~B");
g.addVertex("Huda City Center~Y");
g.addVertex("Saket~Y");
g.addVertex("Vishwavidyalaya~Y");
g.addVertex("Chandni Chowk~Y");
g.addVertex("New Delhi~YO");
g.addVertex("AIIMS~Y");
g.addVertex("Shivaji Stadium~O");
g.addVertex("DDS Campus~O");
g.addVertex("IGI Airport~O");
g.addVertex("Rajouri Garden~BP");
g.addVertex("Netaji Subhash Place~PR");
g.addVertex("Punjabi Bagh West~P");
g.addEdge("Noida Sector 62~B", "Botanical Garden~B", 8);
g.addEdge("Botanical Garden~B", "Yamuna Bank~B", 10);
g.addEdge("Yamuna Bank~B", "Vaishali~B", 8);
g.addEdge("Yamuna Bank~B", "Rajiv Chowk~BY", 6);
g.addEdge("Rajiv Chowk~BY", "Moti Nagar~B", 9);
g.addEdge("Moti Nagar~B", "Janak Puri West~BO", 7);
g.addEdge("Janak Puri West~BO", "Dwarka Sector 21~B", 6);
g.addEdge("Huda City Center~Y", "Saket~Y", 15);
g.addEdge("Saket~Y", "AIIMS~Y", 6);
g.addEdge("AIIMS~Y", "Rajiv Chowk~BY", 7);
g.addEdge("Rajiv Chowk~BY", "New Delhi~YO", 1);
g.addEdge("New Delhi~YO", "Chandni Chowk~Y", 2);
g.addEdge("Chandni Chowk~Y", "Vishwavidyalaya~Y", 5);
g.addEdge("New Delhi~YO", "Shivaji Stadium~O", 2);
g.addEdge("Shivaji Stadium~O", "DDS Campus~O", 7);
g.addEdge("DDS Campus~O", "IGI Airport~O", 8);
g.addEdge("Moti Nagar~B", "Rajouri Garden~BP", 2);
g.addEdge("Punjabi Bagh West~P", "Rajouri Garden~BP", 2);
g.addEdge("Punjabi Bagh West~P", "Netaji Subhash Place~PR", 3);
}
public static String[] printCodelist()
{
System.out.println("List of station along with their codes:\n");
ArrayList<String> keys = new ArrayList<>(vtces.keySet());
int i=1,j=0,m=1;
StringTokenizer stname;
String temp="";
String codes[] = new String[keys.size()];
char c;
for(String key : keys)
{
stname = new StringTokenizer(key);
codes[i-1] = "";
j=0;
while (stname.hasMoreTokens())
{
temp = stname.nextToken();
c = temp.charAt(0);
while (c>47 && c<58)
{
codes[i-1]+= c;
j++;
c = temp.charAt(j);
}
if ((c<48 || c>57) && c<123)
codes[i-1]+= c;
}
if (codes[i-1].length() < 2)
codes[i-1]+= Character.toUpperCase(temp.charAt(1));
System.out.print(i + ". " + key + "\t");
if (key.length()<(22-m))
System.out.print("\t");
if (key.length()<(14-m))
System.out.print("\t");
if (key.length()<(6-m))
System.out.print("\t");
System.out.println(codes[i-1]);
i++;
if (i == (int)Math.pow(10,m))
m++;
}
return codes;
}
public static void main(String[] args) throws IOException
{
Graph_M g = new Graph_M();
Create_Metro_Map(g);
System.out.println("\n\t\t\t****WELCOME TO THE METRO APP*****");
// System.out.println("\t\t\t\t~~LIST OF ACTIONS~~\n\n");
// System.out.println("1. LIST ALL THE STATIONS IN THE MAP");
// System.out.println("2. SHOW THE METRO MAP");
// System.out.println("3. GET SHORTEST DISTANCE FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
// System.out.println("4. GET SHORTEST TIME TO REACH FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
// System.out.println("5. GET SHORTEST PATH (DISTANCE WISE) TO REACH FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
// System.out.println("6. GET SHORTEST PATH (TIME WISE) TO REACH FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
// System.out.print("\nENTER YOUR CHOICE FROM THE ABOVE LIST : ");
BufferedReader inp = new BufferedReader(new InputStreamReader(System.in));
// int choice = Integer.parseInt(inp.readLine());
//STARTING SWITCH CASE
while(true)
{
System.out.println("\t\t\t\t~~LIST OF ACTIONS~~\n\n");
System.out.println("1. LIST ALL THE STATIONS IN THE MAP");
System.out.println("2. SHOW THE METRO MAP");
System.out.println("3. GET SHORTEST DISTANCE FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
System.out.println("4. GET SHORTEST TIME TO REACH FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
System.out.println("5. GET SHORTEST PATH (DISTANCE WISE) TO REACH FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
System.out.println("6. GET SHORTEST PATH (TIME WISE) TO REACH FROM A 'SOURCE' STATION TO 'DESTINATION' STATION");
System.out.println("7. EXIT THE MENU");
System.out.print("\nENTER YOUR CHOICE FROM THE ABOVE LIST (1 to 7) : ");
int choice = -1;
try {
choice = Integer.parseInt(inp.readLine());
} catch(Exception e) {
// default will handle
}
System.out.print("\n***********************************************************\n");
if(choice == 7)
{
System.exit(0);
}
switch(choice)
{
case 1:
g.display_Stations();
break;
case 2:
g.display_Map();
break;
case 3:
ArrayList<String> keys = new ArrayList<>(vtces.keySet());
String codes[] = printCodelist();
System.out.println("\n1. TO ENTER SERIAL NO. OF STATIONS\n2. TO ENTER CODE OF STATIONS\n3. TO ENTER NAME OF STATIONS\n");
System.out.println("ENTER YOUR CHOICE:");
int ch = Integer.parseInt(inp.readLine());
int j;
String st1 = "", st2 = "";
System.out.println("ENTER THE SOURCE AND DESTINATION STATIONS");
if (ch == 1)
{
st1 = keys.get(Integer.parseInt(inp.readLine())-1);
st2 = keys.get(Integer.parseInt(inp.readLine())-1);
}
else if (ch == 2)
{
String a,b;
a = (inp.readLine()).toUpperCase();
for (j=0;j<keys.size();j++)
if (a.equals(codes[j]))
break;
st1 = keys.get(j);
b = (inp.readLine()).toUpperCase();
for (j=0;j<keys.size();j++)
if (b.equals(codes[j]))
break;
st2 = keys.get(j);
}
else if (ch == 3)
{
st1 = inp.readLine();
st2 = inp.readLine();
}
else
{
System.out.println("Invalid choice");
System.exit(0);
}
HashMap<String, Boolean> processed = new HashMap<>();
if(!g.containsVertex(st1) || !g.containsVertex(st2) || !g.hasPath(st1, st2, processed))
System.out.println("THE INPUTS ARE INVALID");
else
System.out.println("SHORTEST DISTANCE FROM "+st1+" TO "+st2+" IS "+g.dijkstra(st1, st2, false)+"KM\n");
break;
case 4:
System.out.print("ENTER THE SOURCE STATION: ");
String sat1 = inp.readLine();
System.out.print("ENTER THE DESTINATION STATION: ");
String sat2 = inp.readLine();
HashMap<String, Boolean> processed1= new HashMap<>();
System.out.println("SHORTEST TIME FROM ("+sat1+") TO ("+sat2+") IS "+g.dijkstra(sat1, sat2, true)/60+" MINUTES\n\n");
break;
case 5:
System.out.println("ENTER THE SOURCE AND DESTINATION STATIONS");
String s1 = inp.readLine();
String s2 = inp.readLine();
HashMap<String, Boolean> processed2 = new HashMap<>();
if(!g.containsVertex(s1) || !g.containsVertex(s2) || !g.hasPath(s1, s2, processed2))
System.out.println("THE INPUTS ARE INVALID");
else
{
ArrayList<String> str = g.get_Interchanges(g.Get_Minimum_Distance(s1, s2));
int len = str.size();
System.out.println("SOURCE STATION : " + s1);
System.out.println("SOURCE STATION : " + s2);
System.out.println("DISTANCE : " + str.get(len-1));
System.out.println("NUMBER OF INTERCHANGES : " + str.get(len-2));
//System.out.println(str);
System.out.println("~~~~~~~~~~~~~");
System.out.println("START ==> " + str.get(0));
for(int i=1; i<len-3; i++)
{
System.out.println(str.get(i));
}
System.out.print(str.get(len-3) + " ==> END");
System.out.println("\n~~~~~~~~~~~~~");
}
break;
case 6:
System.out.print("ENTER THE SOURCE STATION: ");
String ss1 = inp.readLine();
System.out.print("ENTER THE DESTINATION STATION: ");
String ss2 = inp.readLine();
HashMap<String, Boolean> processed3 = new HashMap<>();
if(!g.containsVertex(ss1) || !g.containsVertex(ss2) || !g.hasPath(ss1, ss2, processed3))
System.out.println("THE INPUTS ARE INVALID");
else
{
ArrayList<String> str = g.get_Interchanges(g.Get_Minimum_Time(ss1, ss2));
int len = str.size();
System.out.println("SOURCE STATION : " + ss1);
System.out.println("DESTINATION STATION : " + ss2);
System.out.println("TIME : " + str.get(len-1)+" MINUTES");
System.out.println("NUMBER OF INTERCHANGES : " + str.get(len-2));
//System.out.println(str);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.print("START ==> " + str.get(0) + " ==> ");
for(int i=1; i<len-3; i++)
{
System.out.println(str.get(i));
}
System.out.print(str.get(len-3) + " ==> END");
System.out.println("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
break;
default: //If switch expression does not match with any case,
//default statements are executed by the program.
//No break is needed in the default case
System.out.println("Please enter a valid option! ");
System.out.println("The options you can choose are from 1 to 6. ");
}
}
}
}