-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdijkstrashortreach.java
More file actions
78 lines (65 loc) · 1.99 KB
/
Copy pathdijkstrashortreach.java
File metadata and controls
78 lines (65 loc) · 1.99 KB
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
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for (int t=0; t<tc; t++) {
int totV = sc.nextInt();
int totE = sc.nextInt();
int distances[][] = new int[totV][totV];
boolean visit[] = new boolean[totV];
int minDistances[] = new int[totV];
for (int i=0; i<totV; i++) {
minDistances[i] = Integer.MAX_VALUE;
for (int j=0; j<totV; j++) {
distances[i][j] = Integer.MAX_VALUE;
}
}
for (int i=0; i< totE; i++) {
int v1 = sc.nextInt()-1;
int v2 = sc.nextInt()-1;
int dist = sc.nextInt();
if (dist < distances[v1][v2]) {
distances[v1][v2] = dist;
}
if (dist < distances[v2][v1]) {
distances[v2][v1] = dist;
}
}
int start = sc.nextInt()-1;
int total = 0;
int current = start;
int minDistance = Integer.MAX_VALUE;
minDistances[current] = 0;
while (total < totV) {
total++;
visit[current] = true;
for (int i=0; i<totV; i++) {
if (!visit[i]) {
if (distances[current][i] != Integer.MAX_VALUE && (minDistances[current] + distances[current][i]) < minDistances[i]) {
minDistances[i] = minDistances[current] + distances[current][i];
}
}
}
minDistance = Integer.MAX_VALUE;
for (int i=0; i<totV; i++) {
if (!visit[i] && minDistances[i] < minDistance) {
minDistance = minDistances[i];
current = i;
}
}
}
for (int i=0; i<totV; i++) {
if (i != start) {
if (minDistances[i] == Integer.MAX_VALUE) {
System.out.print("-1 ");
} else {
System.out.print(minDistances[i] + " ");
}
}
}
System.out.println();
}
}
}