TExcelTAD
Home › Graph Algorithms › Transitive Closure

Transitive Closure

Sometimes the weights do not matter, only the question "can ii reach jj at all?" A build system asks which targets must be rebuilt when a file changes; a database asks which employees report, directly or indirectly, to a manager; a type checker asks whether one class is a subclass of another. The answer for every pair at once is the transitive closure of the graph. This lesson computes it three ways: Floyd-Warshall with Boolean operations, one search from every vertex, and the same Boolean algorithm on machine words, which is the fastest of the three for dense graphs.

Definition

The transitive closure of a directed graph G=(V,E)G = (V, E) is the graph G∗=(V,E∗)G^* = (V, E^*) with

E∗={(i,j):there is a path from i to j in G}E^* = \{ (i, j) : \text{there is a path from } i \text{ to } j \text{ in } G \}

Every vertex reaches itself by a path of length 0, so E∗E^* contains all pairs (i,i)(i, i). As a matrix, T=(tij)T = (t_{ij}) with tij=1t_{ij} = 1 exactly when jj is reachable from ii. Row ii of TT is the set of vertices a search from ii finds, as the animation shows for one vertex:

Floyd-Warshall with OR and AND

Run Floyd-Warshall with weight 1 on every edge, and dij<nd_{ij} < n means "reachable". Simpler and faster: replace min⁡\min by logical OR and ++ by logical AND. Let tij(k)=1t_{ij}^{(k)} = 1 if there is a path from ii to jj with all intermediate vertices in {1,…,k}\{1, \ldots, k\}. Then

tij(0)={1if i=j or (i,j)∈E0otherwisetij(k)=tij(k−1)∨(tik(k−1)∧tkj(k−1))t_{ij}^{(0)} = \begin{cases} 1 & \text{if } i = j \text{ or } (i, j) \in E \\ 0 & \text{otherwise} \end{cases} \qquad t_{ij}^{(k)} = t_{ij}^{(k-1)} \lor \left( t_{ik}^{(k-1)} \land t_{kj}^{(k-1)} \right)

This is Warshall's algorithm (1962). It runs in Θ(n3)\Theta(n^3) time like Floyd-Warshall, but works with single bits instead of numbers.

python · try it yourself
names = "ABCDEF"
edges = [("A", "B"), ("B", "C"), ("C", "A"), ("C", "D"), ("D", "E"), ("F", "E"), ("F", "D")]
n = len(names)
T = [[i == j for j in range(n)] for i in range(n)]
for u, v in edges:
    T[names.index(u)][names.index(v)] = True

for k in range(n):
    for i in range(n):
        if T[i][k]:                              # only rows that reach k can gain anything
            for j in range(n):
                T[i][j] = T[i][j] or T[k][j]

print("    " + " ".join(names))
for i in range(n):
    print(f"  {names[i]} " + " ".join("1" if x else "." for x in T[i]))
print("; ".join(f"{v} reaches {''.join(names[j] for j in range(n) if T[i][j] and j != i) or 'nothing else'}"
                for i, v in enumerate(names)))
    A B C D E F
  A 1 1 1 1 1 .
  B 1 1 1 1 1 .
  C 1 1 1 1 1 .
  D . . . 1 1 .
  E . . . . 1 .
  F . . . 1 1 1
A reaches BCDE; B reaches ACDE; C reaches ABDE; D reaches E; E reaches nothing else; F reaches DE

The rows of AA, BB and CC are equal, because the three form a strongly connected component: whatever one of them reaches, all do. EE reaches only itself, and FF, which nobody reaches, reaches DD and EE. In general the closure is determined by the component graph: ii reaches jj exactly when the component of ii reaches the component of jj.

A search from every vertex

For sparse graphs it is faster to run BFS or DFS from each vertex: nn searches of O(V+E)O(V + E) each, so O(V2+VE)O(V^2 + VE), which beats Θ(V3)\Theta(V^3) when EE is much smaller than V2V^2.

Rows as bit vectors

The inner loop of Warshall's algorithm, "row ii = row ii OR row kk", treats a whole row at once. Store each row as a bit vector, and a computer does 64 of those ORs in one machine instruction. That cuts the work by a factor of the word size ww: Θ(n3/w)\Theta(n^3 / w). Python integers are arbitrary-length bit vectors, so the idea takes three lines. The program checks the three methods against each other on random graphs and counts their elementary steps: edge looks for the searches, single-bit operations for the plain Warshall loop, and word operations (64 bits each) for the bit-vector version.

python · try it yourself
import random

def warshall_bits(n, adj):
    rows = [(1 << i) | sum(1 << j for j in adj[i]) for i in range(n)]
    words = (n + 63) // 64
    ops = 0
    for k in range(n):
        bit = 1 << k
        rk = rows[k]
        for i in range(n):
            if rows[i] & bit:
                rows[i] |= rk
                ops += words                   # one OR per 64-bit word of the row
    return rows, ops

def warshall_plain(n, adj):
    T = [[i == j or j in adj[i] for j in range(n)] for i in range(n)]
    ops = 0
    for k in range(n):
        for i in range(n):
            if T[i][k]:
                Ti, Tk = T[i], T[k]
                for j in range(n):
                    Ti[j] = Ti[j] or Tk[j]
                ops += n
    return [sum(1 << j for j in range(n) if T[i][j]) for i in range(n)], ops

def search_each(n, adj):
    rows, looks = [], 0
    for s in range(n):
        seen, stack = 1 << s, [s]
        while stack:
            u = stack.pop()
            for v in adj[u]:
                looks += 1
                if not seen >> v & 1:
                    seen |= 1 << v
                    stack.append(v)
        rows.append(seen)
    return rows, looks

rng = random.Random(19)
print(f"{'n':>4} {'E':>6} {'searches':>9} {'plain Warshall':>15} {'bit rows':>9}  reachable pairs")
for n, p in [(60, 0.03), (60, 0.3), (180, 0.01), (180, 0.2)]:
    adj = [[v for v in range(n) if v != u and rng.random() < p] for u in range(n)]
    E = sum(len(a) for a in adj)
    a, c1 = search_each(n, adj)
    b, c2 = warshall_plain(n, adj)
    c, c3 = warshall_bits(n, adj)
    assert a == b == c
    pairs = sum(bin(r).count("1") for r in a)
    print(f"{n:>4} {E:>6} {c1:>9,} {c2:>15,} {c3:>9,}  {pairs:,} of {n * n:,}")
   n      E  searches  plain Warshall  bit rows  reachable pairs
  60     99     2,259          31,380       523  1,492 of 3,600
  60   1064    63,840         206,760     3,446  3,600 of 3,600
 180    326    36,376       1,150,740    19,179  19,444 of 32,400
 180   6360 1,144,800       5,558,220    92,637  32,400 of 32,400

The searches always beat the plain Warshall loop, by a large factor on the sparse graphs. Counted in word operations, the bit-vector version is the cheapest in every run, because a row of 60 or 180 bits fits in one to three words, so each OR does the work of up to 180 single-bit steps. Asymptotically the picture is O(V2+VE)O(V^2 + VE) for the searches against Θ(V3/w)\Theta(V^3 / w) for the bit rows: on very large sparse graphs, with EE much smaller than V2/wV^2 / w, the searches win again. Reachability libraries often shrink the graph first to its component graph, then use bit rows.

In C++

std::bitset gives fixed-size bit vectors with a word-parallel |=. The program computes the closure of the lesson's graph and answers two queries.

cpp · try it yourself
#include <bitset>
#include <cstdio>
#include <string>
#include <vector>

int main() {
    const std::string names = "ABCDEF";
    const int n = static_cast<int>(names.size());
    std::vector<std::bitset<64>> row(n);
    for (int i = 0; i < n; ++i) row[i].set(i);
    for (auto [u, v] : std::vector<std::pair<char, char>>{{'A','B'}, {'B','C'}, {'C','A'}, {'C','D'},
                                                         {'D','E'}, {'F','E'}, {'F','D'}})
        row[u - 'A'].set(v - 'A');
    for (int k = 0; k < n; ++k)
        for (int i = 0; i < n; ++i)
            if (row[i][k]) row[i] |= row[k];
    for (int i = 0; i < n; ++i) {
        std::printf("%c reaches", names[i]);
        for (int j = 0; j < n; ++j) if (row[i][j]) std::printf(" %c", names[j]);
        std::printf(" (%zu in all)\n", row[i].count());
    }
    std::printf("A -> E? %s   E -> A? %s\n", row[0][4] ? "yes" : "no", row[4][0] ? "yes" : "no");
}
A reaches A B C D E (5 in all)
B reaches A B C D E (5 in all)
C reaches A B C D E (5 in all)
D reaches D E (2 in all)
E reaches E (1 in all)
F reaches D E F (3 in all)
A -> E? yes   E -> A? no

Test yourself

What is the transitive closure of a directed graph?

  1. The graph with every edge reversed
  2. The graph with an edge (i,j)(i, j) whenever jj is reachable from ii
  3. A minimum spanning tree
  4. The strongly connected components

Which operations replace min⁡\min and ++ when Floyd-Warshall computes the transitive closure?

  1. max⁡\max and ⋅\cdot
  2. OR and AND
  3. XOR and OR
  4. ++ and ⋅\cdot

For a sparse graph with E=O(V)E = O(V), which method computes the closure fastest asymptotically?

  1. Warshall's algorithm, Θ(V3)\Theta(V^3)
  2. A BFS or DFS from every vertex, O(V2+VE)=O(V2)O(V^2 + VE) = O(V^2)
  3. Repeated squaring
  4. Johnson's algorithm

Why do the rows of AA, BB and CC in the example's closure matrix coincide?

  1. They have the same out-degree
  2. They form a strongly connected component, so each reaches everything the others reach
  3. Because the matrix is symmetric
  4. By coincidence