Floyd-Warshall: all shortest paths

前端 未结 2 1418
广开言路
广开言路 2021-02-04 07:47

I\'ve implemented Floyd-Warshall to return the distance of the shortest path between every pair of nodes/vertices and a single shortest path between each of the

2条回答
  •  后悔当初
    2021-02-04 08:47

    The 'counting' function in the current approved answer flails in some cases. A more complete solution would be:

    procedure FloydWarshallWithCount ()
    for k := 1 to n
        for i := 1 to n
            for j := 1 to n
                if path[i][j] == path[i][k]+path[k][j]
                    count[i][j] += count[i][k] * count[k][j]
                else if path[i][j] > path[i][k] + path[k][j]
                    path[i][j] = path[i][k] + path[k][j]
                    count[i][j] = count[i][k] * count[k][j]
    

    The reason for this is that for any three vertices i, j, and k, there may be multiple shortest paths that run from i through k to j. For instance in the graph:

           3             1
    (i) -------> (k) ---------> (j)
     |            ^
     |            |
     | 1          | 1
     |     1      |
    (a) -------> (b)
    

    Where there are two paths from i to j through k. count[i][k] * count[k][j] finds the number of paths from i to k, and the number of paths from k to j, and multiplies them to find the number of paths i -> k -> j.

提交回复
热议问题