3

How would I get every single shortest path from vertex 1 to vertex 10 which has the same weight using the Floyd-Warshall algorithm? I managed to get total numbers of all shortest path from vertex 1 to vertex 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];
}
Tuan Pham
  • 133
  • 1
  • 1
  • 9

1 Answers1

1

Use the algorithm once to find the weighted length for every vertex of the shortest path from v1.

Use the algorithm again to find the weighted length for every vertex of the shortest path to v10.

All vertices which are on a shortest path will have the sum of those two weighted lengths equal to the weighted length from v1 to v10. A directed edge is on a shortest path if and only both vertices are on shortest paths and the weight of the original edge is the difference in weighted length from v1.

This will give you a directed subgraph of everything on shortest paths, with most of the cost being the two runs of the basic algorithm. You can enumerate it recursively. Do be warned that there can be a lot of shortest paths, and therefore the enumeration itself can take exponentially long to run.

btilly
  • 43,296
  • 3
  • 59
  • 88