Transitive closure and shortest paths

Let G = (V,E) be a directed graph represented by adjacency matrix A.   Define G* = (V,E*), represented by adjacency matrix A*, to be a directed graph on the same vertex set but with edge set defined by (x,y in E* iff the exists a path x to y in G.   G* is the reflexive transitive closure of G.

Similarly, G+ is the irreflexive transitive closure of G, defined by edge set E+ with (x,y in E+ iff the exists a path with at least one edge from x to y in G.

We can evaluate A* as follows.

   forall i,j in [1...n] do
      A0[i,j] := A[i,j]
      /** delete the next line to calculate A+ **/
   for i := 1 to n do A0[i,i] := 1
   for k := 1 to n do
      for i := 1 to n do
         for j := 1 to n do
            Ak[i,j] := Ak-1[i,j] or (Ak-1[i,k] and Ak-1[k,j])
   forall i,j in [1...n] do
      A*[i,j] := An[i,j]

The time complexity of this algorithm is O(n3).

Ak[i, j] = 1 iff there exists a path from i to j with all intermediate vertices being labeled with numbers that are at most k.

All-pairs shortest paths

Given costs on the edges of a graph, we wish to find the minimum cost paths from any vertex to every other vertex.   An algorithm to do this is very similar to the algorithm just described for computing transitive closure.

The input is a distance matrix, dist.

   forall i,j in [1...n] do
      C[i,j] := dist[i,j]
      P[i,j] := j
   for i := 1 to n do
      C[i,i] := 0
   for k := 1 to n do
      for i := 1 to n do
         for j := 1 to n do
            if C[i,k] + C[k,j] < C[i,j] then
               C[i,j] := C[i,k] + C[k,j]
               P[i,j] := P[i,k]

The time complexity of this algorithm is O(n3).

The minimum cost of a path from i to j is C[i, j].   The path is v0, v0, ... with v0 = i and, for all k, vk+1 = P[vk, j].

This algorithm allows negative edge costs.   However, negative cycles are not allowed (otherwise there would be no minimum cost).

This algorithm is the best known even for finding a singlepath.   If we allow only positive edge costs, there is an O(n3[(log log n)/log n]1/3) algorithm -- SICOMP March 1976, p.83.   If we allow only unit edge cost, there is an O(n2.36log n) algorithm -- STOC 1992, 745-749.


Dan Hirschberg
Last modified: Mar 3, 2005