题目与思路:
代码:
import java.util.Scanner;
public class FloydAlgorithm {
public static void main(String[] args) {
//定义距离矩阵
int d[][] = new int[100][100];
for (int i=0;i<100;i++){
for (int j=0;j<100;j++){
d[i][j] = ((i==j) ? 0 : Integer.MAX_VALUE);
}
}
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int e = cin.nextInt();
for (int i=0;i<e;i++){
int u = cin.nextInt();
int v = cin.nextInt();
int c = cin.nextInt();
d[u][v] = c;
}
floyd(d, n);
boolean negative = false;
for (int i=0;i<n;i++)if(d[i][i]<0) negative = true;
if (negative){
System.out.println("NEGATIVE CYCLE");
}else{
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
if(j!=0) System.out.print(" ");
if (d[i][j]==Integer.MAX_VALUE) System.out.print("INF");
else System.out.print(d[i][j]);
}
System.out.println();
}
}
}
public static void floyd(int[][] d, int n){
for (int k=0;k<n;k++){
for (int i=0;i<n;i++){
if(d[i][k]==Integer.MAX_VALUE)continue;
for (int j=0;j<n;j++){
if (d[k][j]==Integer.MAX_VALUE)continue;
d[i][j] = Math.min(d[i][j], d[i][k]+d[k][j]);
}
}
}
}
}
输入1:
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 7
输出1:
0 1 3 4
INF 0 2 3
INF INF 0 1
INF INF 7 0
输入2:
4 6
0 1 1
0 2 -5
1 2 2
1 3 4
2 3 1
3 2 7
输出2:
0 1 -5 -4
INF 0 2 3
INF INF 0 1
INF INF 7 0
输入3:
4 6
0 1 1
0 2 5
1 2 2
1 3 4
2 3 1
3 2 -7
输出3:
NEGATIVE CYCLE