给定一个带权有向图,计算任意两结点间的最短路径。
算法思想:遍历每个点到另外点的距离。三层循环,第一层枚举中间点,第二层和第三层枚举起点和终点。
public static void main() {
int N = 1010, M = 2000010, INF = 1000000000;
int[][] d = new int[N][N]; // 存储两点之间的最短距离
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
d[i][j] = i == j ? 0 : INF;
for (int i = 0; i < m; i++) {
int a, b, c;
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
d[a][b] = d[b][a] = Math.min(c, d[a][b]);
}
// floyd 算法核心
for (int k = 1; k <= n; k++) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
d[i][j] = Math.min(d[i][j], d[i][k] + d[k][j]);
}
}
}
System.out.println(d[1][n]);
}