-
Notifications
You must be signed in to change notification settings - Fork 0
/
floydWarshall.java
56 lines (43 loc) · 1.34 KB
/
floydWarshall.java
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
package graph;
import java.util.*;
// all pairs shortest path
// negative edges allowed
// dist[i][j] == -inf if goes through negative cycle
// O(N^3)
public class floydWarshall {
long inf = Long.MAX_VALUE/2;
long[][] dist;
int n;
floydWarshall(int n){
n = n;
dist = new long[n][n];
for(int i = 0; i < n; i++){Arrays.fill(dist[i], inf);dist[i][i] = 0;}
}
void addEdge(int u, int v, int w){
dist[u][v] = Math.min(dist[u][v],w);
}
void fWarshall(){
for(int k = 0; k < n; k++){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(dist[i][k] != inf && dist[k][j] != inf){
long newD = Math.max(dist[i][k] + dist[k][j], -inf);
dist[i][j] = Math.min(newD, dist[i][j]);
}
}
}
}
// negative self loop
for(int k = 0; k < n; k++){
if(dist[k][k] < 0){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(dist[i][k] != inf && dist[k][j] != inf){
dist[i][j] = -inf;
}
}
}
}
}
}
}