1
1
public static void main (String [] args ) throws IOException {
2
2
Reader in =new Reader ();
3
3
int t1 =in .nextInt ();
4
- for (int gj =0 ;gj <t1 ;gj ++)
5
- {
6
- int n =in .nextInt ();
7
- int m =in .nextInt ();
8
- long w [][]=new long [n +1 ][n +1 ];
9
- for (long [] row : w )
4
+
5
+ int n =in .nextInt (); //n = Number of nodes or vertices
6
+ int m =in .nextInt (); //m = Number of Edges
7
+ long w [][]=new long [n +1 ][n +1 ]; //Adjacency Matrix
8
+
9
+ //Initializing Matrix with Certain Maximum Value for path b/w any two vertices
10
+ for (long [] row : w )
10
11
Arrays .fill (row , 1000000l );
12
+ //From above,we Have assumed that,initially path b/w any two Pair of vertices is Infinite such that Infinite = 1000000l
13
+ //For simplicity , We can also take path Value = Long.MAX_VALUE , but i have taken Max Value = 1000000l .
14
+
15
+ //Taking Input as Edge Location b/w a pair of vertices
11
16
for (int i =0 ;i <m ;i ++){
12
17
int x =in .nextInt (),y =in .nextInt ();
13
18
long cmp =in .nextLong ();
14
- if (w [x ][y ]>cmp ){
15
- w [x ][y ]=cmp ; w [y ][x ]=cmp ;
19
+ if (w [x ][y ]>cmp ){ //Comparing previous edge value with current value - Cycle Case
20
+ w [x ][y ]=cmp ; w [y ][x ]=cmp ;
16
21
}
17
22
}
23
+
24
+ //Implementing Dijkshtra's Algorithm
25
+
18
26
Stack <Integer > t =new Stack <Integer >();
19
27
int src =in .nextInt ();
20
28
for (int i =1 ;i <=n ;i ++){
@@ -30,9 +38,11 @@ public static void main(String[] args) throws IOException {
30
38
min =(int ) w [src ][t .elementAt (i )];loc =i ;}
31
39
}
32
40
p .push (t .elementAt (loc ));t .removeElementAt (loc );}
41
+
42
+ //Printing shortest path from the given source src
33
43
for (int i =1 ;i <=n ;i ++){
34
44
if (i !=src && w [src ][i ]!=1000000l ){System .out .print (w [src ][i ]+" " );}
35
- else if (i !=src ){System .out .print ("-1" +" " );}
36
- }System .out .println ();
45
+ else if (i !=src ){System .out .print ("-1" +" " );} //Printing -1 if there is no path b/w given pair of edges
37
46
}
47
+
38
48
}
0 commit comments