Floyd-Warshall路径重建没有递归

时间:2018-05-24 21:06:38

标签: java algorithm floyd-warshall

我正在使用here中的Floyd-Warshall算法。

import static java.lang.String.format;
import java.util.Arrays;



public class FloydWarshall {


    public static void main(String[] args) {
        int[][] weights = {{1, 3, -2}, {2, 1, 4}, {2, 3, 3}, {3, 4, 2}, {4, 2, -1}};
        int numVertices = 4;

        floydWarshall(weights, numVertices);
    }

    static void floydWarshall(int[][] weights, int numVertices) {

        double[][] dist = new double[numVertices][numVertices];
        for (double[] row : dist)
            Arrays.fill(row, Double.POSITIVE_INFINITY);

        for (int[] w : weights)
            dist[w[0] - 1][w[1] - 1] = w[2];

        int[][] next = new int[numVertices][numVertices];
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++)
                if (i != j)
                    next[i][j] = j + 1;
        }

        for (int k = 0; k < numVertices; k++)
            for (int i = 0; i < numVertices; i++)
                for (int j = 0; j < numVertices; j++)
                    if (dist[i][k] + dist[k][j] < dist[i][j]) {
                        dist[i][j] = dist[i][k] + dist[k][j];
                        next[i][j] = next[i][k];
                    }

        printResult(dist, next);
    }

    static void printResult(double[][] dist, int[][] next) {
        System.out.println("pair     dist    path");
        for (int i = 0; i < next.length; i++) {
            for (int j = 0; j < next.length; j++) {
                if (i != j) {
                    int u = i + 1;
                    int v = j + 1;
                    String path = format("%d -> %d    %2d     %s", u, v,
                            (int) dist[i][j], u);
                    do {
                        u = next[u - 1][v - 1];
                        path += " -> " + u;
                    } while (u != v);
                    System.out.println(path);
                }
            }
        }
    }
}

算法本身很清楚,但我不明白的是next矩阵。根据我对i,j索引的理解,索引应该是从节点i到节点j的路径上的最后一个节点。然后递归打印打印路径。但是这段代码在打印语句printResult中使用了某种不同的方法。所以我的问题是矩阵next究竟是什么以及打印如何工作?

1 个答案:

答案 0 :(得分:0)

dist[i][j] = dist[i][k] + dist[k][j]说:当从i到j时,经过k,从i到k的最短路径,然后是从k到j的最短路径。在这里:next[i][j] = next[i][k]它说当从i到j时,如果你从i到k,首先去你想去的地方。

所以,行u = next[u - 1][v - 1];说:你现在是从u到v的路径上的下一个节点。