Skip to content

Commit 8426d22

Browse files
author
Mayank Kumar Jha
authored
Add files via upload
1 parent 8ef3d70 commit 8426d22

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Dijkshtra.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
public static void main(String[] args) throws IOException {
2+
Reader in=new Reader();
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)
10+
Arrays.fill(row, 1000000l);
11+
for(int i=0;i<m;i++){
12+
int x=in.nextInt(),y=in.nextInt();
13+
long cmp=in.nextLong();
14+
if(w[x][y]>cmp){
15+
w[x][y]=cmp; w[y][x]=cmp;
16+
}
17+
}
18+
Stack <Integer> t=new Stack<Integer>();
19+
int src=in.nextInt();
20+
for(int i=1;i<=n;i++){
21+
if(i!=src){t.push(i);}}
22+
Stack <Integer> p=new Stack<Integer>();
23+
p.push(src);
24+
w[src][src]=0;
25+
while(!t.isEmpty()){int min=989997979,loc=-1;
26+
for(int i=0;i<t.size();i++){
27+
w[src][t.elementAt(i)]=Math.min(w[src][t.elementAt(i)],w[src][p.peek()]
28+
+w[p.peek()][t.elementAt(i)]);
29+
if(w[src][t.elementAt(i)]<=min){
30+
min=(int) w[src][t.elementAt(i)];loc=i;}
31+
}
32+
p.push(t.elementAt(loc));t.removeElementAt(loc);}
33+
for(int i=1;i<=n;i++){
34+
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();
37+
}
38+
}

0 commit comments

Comments
 (0)