Transitive Closure
Sometimes the weights do not matter, only the question "can reach 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 is the graph with
Every vertex reaches itself by a path of length 0, so contains all pairs . As a matrix, with exactly when is reachable from . Row of is the set of vertices a search from finds, as the animation shows for one vertex:
Floyd-Warshall with OR and AND
Run Floyd-Warshall with weight 1 on every edge, and means "reachable". Simpler and faster: replace by logical OR and by logical AND. Let if there is a path from to with all intermediate vertices in . Then
This is Warshall's algorithm (1962). It runs in time like Floyd-Warshall, but works with single bits instead of numbers.
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 , and are equal, because the three form a strongly connected component: whatever one of them reaches, all do. reaches only itself, and , which nobody reaches, reaches and . In general the closure is determined by the component graph: reaches exactly when the component of reaches the component of .
A search from every vertex
For sparse graphs it is faster to run BFS or DFS from each vertex: searches of each, so , which beats when is much smaller than .
Rows as bit vectors
The inner loop of Warshall's algorithm, "row = row OR row ", 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 : . 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.
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 for the searches against for the bit rows: on very large sparse graphs, with much smaller than , 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.
#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?
- The graph with every edge reversed
- The graph with an edge whenever is reachable from
- A minimum spanning tree
- The strongly connected components
Which operations replace and when Floyd-Warshall computes the transitive closure?
- and
- OR and AND
- XOR and OR
- and
For a sparse graph with , which method computes the closure fastest asymptotically?
- Warshall's algorithm,
- A BFS or DFS from every vertex,
- Repeated squaring
- Johnson's algorithm
Why do the rows of , and in the example's closure matrix coincide?
- They have the same out-degree
- They form a strongly connected component, so each reaches everything the others reach
- Because the matrix is symmetric
- By coincidence