import java.util.Scanner;
/**
* Created by wjz on 2017/3/25.
* 多源最短路径算法:Floyd算法
*/
public class Main4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] dist = new int[n][n];
int[][] pre = new int[n][n];
int[][] min = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = sc.nextInt();
}
}
min = floyd(dist,min,n,pre);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(min[i][j] + " ");
}
System.out.println();
}
}
/**
* @param dist 邻接矩阵
* @param min 结果
* @param n 节点数量
* @param pre 路径 pre[i][j]表示i到j节点的路径前一节点
* @return
*/
static int[][] floyd(int[][] dist,int[][] min, int n, int[][] pre) {
//初始化
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
min[i][j] = dist[i][j];
pre[i][j] = (i==j) ? -1 : i;
}
}
//i为中间节点
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
if (min[j][k] > min[j][i] + min[i][k]) {
min[j][k] = min[j][i] + min[i][k];
pre[j][k] = pre[i][k];
}
}
}
}
return min;
}
}
Floyd多源最短路径算法
最新推荐文章于 2020-11-30 11:03:07 发布