Skip to content

Floyd-Warshall

Summarized notes from Introduction to Algorithms, Chapter 25

  • graph may include negative weights, no negative-weight cycles
  • considers intermediate vertices of path p
    • intermediate is any vertex other than v1 or vl: {v2,v3,...vl1}
    • if k is not an intermediate vertex pf p, then all intermediate vertices are in set {1,2,...,k1}
    • if k is an intermediate vertex, then decompose p:

img

di,jk is weight of shortest path from vertex i to j for which all intermediate vertices are in the set {1,2,...,k1}, defined recursively by:

di,j(k)={wijif k=0,min(di,j(k1),di,k(k1)+dk,j(k1))if k1.
  • compute di,jk in order of increasing values of k
  • input is n×n matrix
  • output is D(n) matrix of shortest path weights

Implementation

1
2
3
4
5
6
7
8
9
FLOYD-WARSHALL(W)
    n = W.rows
    D^0 = W
    for k = 1 to n
        let D^k = (d_ij^k) be a new n x n matrix
        for i = 1 to n
            for j = 1 to n
                d_ij^k = min(d_ij^(k-1), d_ik^(k-1) + d_kj^(k-1))
    return D^n

Complexity

Running Time
Θ(V3) Floyd-Warshall

Constructing shortest path

  • One strategy: compute D then construct predecessor matrix from D
  • Another strategy: compute during Floyd-Warshall while constructing D

img

Transitive closure

  • Determines if path from i to j exists
  • Transitive closure of G is G=(V,E) where E={(i,j) : there is a path from i to j in G }
  • Compute in Θ(V3) time: assign weight 1 to each edge and run Floyd-Warshall → when path exists di,j<
  • Another strategy that can be faster and more space efficient:
    • substitute logical-OR and logical-AND for operations min and +

when k=0

tij(0)={0if ij and (i,j)E,1if i=j or (i,j)E

and for k1,

tij(0)=tij(k1)(tik(k1)tkj(k1))

Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
TRANSITIVE-CLOSURE(G)
    n = |G.V|
    let T^0 = t_ij^(0) be a new n x n matrix
    for i = 1 to n
        for j = 1 to n
            if i == j or (i,j) in G.E
                t_ij^(0) = 1
            else
                t_ij^(0) = 0
    for k = 1 to n
        let T^k = t_ij^(k) be a new n x n matrix
        for i = 1 to n
            for j = 1 to n
                t_ij^(k) = t_ij^(k-1) or (t_ik^(k-1) and t_kj^(k-1))
    return T^n

Complexity

Running Time
Θ(V3) Transitive closure