forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFloydWarshall.java
More file actions
45 lines (41 loc) · 1.17 KB
/
FloydWarshall.java
File metadata and controls
45 lines (41 loc) · 1.17 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
public class FloydWarshall {
static final int INF = Integer.MAX_VALUE / 2;
// precondition: d[i][i] == 0
public static int[][] floydWarshall(int[][] d) {
int n = d.length;
int[][] pred = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
pred[i][j] = (i != j && d[i][j] != INF) ? i : -1;
for (int k = 0; k < n; k++) {
for (int i = 0; i < n; i++) {
if (d[i][k] == INF)
continue;
for (int j = 0; j < n; j++) {
if (d[k][j] == INF)
continue;
if (d[i][j] > d[i][k] + d[k][j]) {
d[i][j] = d[i][k] + d[k][j];
d[i][j] = Math.max(d[i][j], -INF);
pred[i][j] = pred[k][j];
}
}
}
}
for (int i = 0; i < n; i++)
if (d[i][i] < 0)
return null;
return pred;
}
// Usage example
public static void main(String[] args) {
int[][] dist = {{0, 3, 2}, {0, 0, 1}, {INF, 0, 0}};
int[][] pred = floydWarshall(dist);
System.out.println(0 == dist[0][0]);
System.out.println(2 == dist[0][1]);
System.out.println(2 == dist[0][2]);
System.out.println(-1 == pred[0][0]);
System.out.println(2 == pred[0][1]);
System.out.println(0 == pred[0][2]);
}
}