将每个顶点之间的距离做成一个矩阵
int[][] matrix = { {0,5,2,inf,inf,inf,inf}, {5,2,inf,1,6,inf,inf}, {2,inf,0,6,inf,8,inf}, {inf,1,6,0,1,2,inf}, {inf,6,inf,1,0,inf,7}, {inf,inf,8,2,inf,0,3}, {inf,inf,inf,inf,7,3,0}, };
更新最短距离
Math.min()将两者进行比较选择最小的存入矩阵
Math.min(matrix[i][j],matrix[i][k]+matrix[k][j]);
所有代码:
public class as {
final static int inf = Integer.MAX_VALUE; public static void floyd(int[][] matrix){ //跟新最短路径 for(int k = 0 ;k<matrix.length;k++){ for(int i = 0;i<matrix.length;i++){ for(int j=0;j<matrix.length;j++){ if(matrix[i][k]== inf||matrix[k][j]==inf){ continue; } matrix[i][j]= Math.min(matrix[i][j],matrix[i][k]+matrix[k][j]); } } System.out.println("最短路径矩阵:\n"); for(int i = 0;i<matrix.length;i++){ for (int j =0;j<matrix.length;j++){ System.out.print(matrix[i][j]+" "); } System.out.println("\n"); } } } public static void main(String[] args) { int[][] matrix = { {0,5,2,inf,inf,inf,inf}, {5,2,inf,1,6,inf,inf}, {2,inf,0,6,inf,8,inf}, {inf,1,6,0,1,2,inf}, {inf,6,inf,1,0,inf,7}, {inf,inf,8,2,inf,0,3}, {inf,inf,inf,inf,7,3,0}, }; floyd(matrix); } }
原文地址:https://www.cnblogs.com/BigFF/p/10795544.html
时间: 2024-10-16 19:00:10