algorithm - Floyd-Warshall: all shortest paths -
i've implemented floyd warshall return distance of shortest path between every pair of nodes/vertices , return me (but one) shortest path between each of these pairs. there anyway return every shortest path (when there multiple tied shortest) every pair of nodes? (just want know if i'm wasting time trying)
if need count of how many different shortest path exist, can keep count
array in addition shortestpath
array. here's quick modification of pseudocode wiki.
procedure floydwarshall () k := 1 n := 1 n j := 1 n if path[i][j] == path[i][k]+path[k][j] , k != j , k != count[i][j] += 1; else if path[i][j] > path[i][k] + path[k][j] path[i][j] = path[i][k] + path[k][j] count[i][j] = 1
if need way find paths, can store vector/arraylist
structure each pair expand , collapse. here modification of pseudocode same wiki.
procedure floydwarshallwithpathreconstruction () k := 1 n := 1 n j := 1 n if path[i][k] + path[k][j] < path[i][j] path[i][j] := path[i][k]+path[k][j]; next[i][j].clear() next[i][j].push_back(k) // assuming c++ vector else if path[i][k] + path[k][j] == path[i][j] , k != j , k != next[i][j].push_back(k)
note: if k==j
or k==i
, means, you're checking either path[i][i]+path[i][j]
or path[i][j]+path[j][j]
, both should equal path[i][j]
, not pushed next[i][j]
.
path reconstruction should modified handle vector
. count in case each vector
's size. here modification of pseudocode (python) same wiki.
procedure getpath(i, j): allpaths = empty 2d array if next[i][j] not empty: every k in next[i][j]: if k == -1: // add path = [i, j] allpaths.add( array[ i, j] ) else: // add path = [i .. k .. j] paths_i_k = getpath(i,k) // paths k paths_k_j = getpath(k,j) // paths k j every path between , k, i_k in paths_i_k: every path between k , j, k_j in paths_k_j: i_k = i_k.popk() // remove last element since repeats in k_j allpaths.add( array( i_k + j_k) ) return allpaths
note: path[i][j]
adjacency list. while initializing path[i][j]
, can initialize next[i][j]
adding -1
array. instance initialization of next[i][j]
for every edge (i,j) in graph: next[i][j].push_back(-1)
this takes care of edge being shortest path itself. you'll have handle special case in path reconstruction, i'm doing in getpath
.
Comments
Post a Comment