Floyd-Warshall算法返回具有相同权重的每条最短路径

时间:2018-04-17 17:28:02

标签: java algorithm floyd-warshall

如何使用Floyd-Warshall算法从顶点1到顶点10获得具有相同权重的每条最短路径? 我设法得到从顶点1到顶点10的所有最短路径的总数。

public static int[][] shortestpath(int[][] adj, int[][] path, int[][] count) {

    int n = adj.length;
    int[][] ans = new int[n][n];

    copy(ans, adj);

    // Compute incremently better paths through vertex k.
    for (int k = 0; k < n; k++) {

        // Iterate through each possible pair of points.
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {

                // Check if it is better to go through k as an intermediate vertex.
                if (ans[i][k] + ans[k][j] < ans[i][j]) {
                    ans[i][j] = ans[i][k] + ans[k][j];
                    path[i][j] = path[k][j];
                    count[i][j] = count[i][k]*count[k][j];
                } else if ((ans[i][j] == ans[i][k]+ans[k][j]) && (k!=j) && (k!=i)) {
                    count[i][j] += count[i][k]*count[k][j];
                }
            }
        }
    }

    // Return the shortest path matrix.
    return ans;
}

public static void copy(int[][] a, int[][] b) {
    for (int i = 0; i < a.length; i++)
        for (int j = 0; j < a[0].length; j++)
            a[i][j] = b[i][j];
}

1 个答案:

答案 0 :(得分:1)

使用算法一次,找到v1最短路径的每个顶点的加权长度。

再次使用算法查找到v10的最短路径的每个顶点的加权长度。

在最短路径上的所有顶点将具有这两个加权长度的总和,其等于从v1到v10的加权长度。如果且只有两个顶点都在最短路径上并且原始边缘的权重是加权长度与v1的差异,则定向边缘位于最短路径上。

这将为您提供最短路径上所有内容的有向子图,其中大部分成本是基本算法的两次运行。你可以递归地枚举它。请注意,可能存在许多最短路径,因此枚举本身可能需要指数级运行。

相关问题