Skip to content

Commit 9d2374f

Browse files
author
Mayank Kumar Jha
authored
Dijkshtra's Algorithm
1 parent 8426d22 commit 9d2374f

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

Dijkshtra.java

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,28 @@
11
public static void main(String[] args) throws IOException {
22
Reader in=new Reader();
33
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)
1011
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
1116
for(int i=0;i<m;i++){
1217
int x=in.nextInt(),y=in.nextInt();
1318
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;
1621
}
1722
}
23+
24+
//Implementing Dijkshtra's Algorithm
25+
1826
Stack <Integer> t=new Stack<Integer>();
1927
int src=in.nextInt();
2028
for(int i=1;i<=n;i++){
@@ -30,9 +38,11 @@ public static void main(String[] args) throws IOException {
3038
min=(int) w[src][t.elementAt(i)];loc=i;}
3139
}
3240
p.push(t.elementAt(loc));t.removeElementAt(loc);}
41+
42+
//Printing shortest path from the given source src
3343
for(int i=1;i<=n;i++){
3444
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
3746
}
47+
3848
}

0 commit comments

Comments
 (0)