Skip to content

Commit be92cbc

Browse files
Merge pull request #30 from mk9440/master
Dijkshtra's Algorithm
2 parents 2bb2307 + a7cef0c commit be92cbc

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Dijkshtra.java

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

0 commit comments

Comments
 (0)