Sub topic 16
Transitive Closure as a Floyd-Warshall Variant
This chapter assumes you already know the Floyd-Warshall recurrence over intermediate vertices and its triple loop from the earlier chapters. You should also be comfortable reading adjacency matrices and Python lists of lists.
Sometimes you do not care how long a path is, only whether one exists. Some examples: can module A end up importing module B through any chain of imports? Can user X reach resource Y through some sequence of permission grants? Which tasks must finish before task T can start? Each of these is a reachability question. Answering it for every pair of vertices at once is called computing the transitive closure of the graph.
What Transitive Closure Means
The transitive closure of a directed graph G is a new graph G on the same vertices. G has an edge i → j exactly when G has a path of one or more edges from i to j. We usually store it as a boolean matrix reach, where reach[i][j] is True when j is reachable from i.
Two conventions are in common use, and mixing them up is a frequent source of bugs:
| Convention | Diagonal `reach[i][i]` | Meaning |
|---|---|---|
| Strict (paths of length ≥ 1) | `True` only if i lies on a cycle | "Can I leave i and come back?" |
| Reflexive (paths of length ≥ 0) | Always `True` | "Can I be at i starting from i?" (trivially yes) |
This chapter uses the strict convention. With it, the diagonal tells you something useful, much as the Floyd-Warshall diagonal flags negative cycles. To get the reflexive closure, set every diagonal entry to True at the end.
From (min, +) to (OR, AND)
Floyd-Warshall builds dist[i][j] in stages. After stage k, the entry holds the best path from i to j whose intermediate vertices all come from {0, …, k}. The update is:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
For reachability, you swap the two operations:
- "Best of two options" (
min) becomes "either option works" (or). - "Join two path pieces" (
+) becomes "both pieces must exist" (and).
reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j])
This boolean form is known as Warshall's algorithm. It predates Floyd's weighted version. The correctness argument is the same one you saw before. Suppose a path from i to j uses only intermediates up to k. Either it avoids k, so the previous stage already found it, or it passes through k, so it splits into an i → k piece and a k → j piece that each use only intermediates below k.
| Aspect | Floyd-Warshall | Warshall (transitive closure) |
|---|---|---|
| Entry type | number (or ∞) | boolean |
| Initial value, edge u → v | weight w | `True` |
| Initial value, no edge | ∞ | `False` |
| Combine alternatives | `min` | `or` |
| Extend a path | `+` | `and` |
| Diagonal signal | `dist[i][i] < 0` means a negative cycle | `reach[i][i]` means i is on a cycle |
| Time | O(V³) | O(V³), or O(V³ / w) with bitsets |
A Worked Example
Take a graph with four vertices and the edges 0 → 1, 1 → 2, 2 → 0, and 2 → 3. Vertices 0, 1, and 2 form a cycle, and vertex 3 is a sink with no outgoing edges.
Every vertex in the cycle can reach every vertex in the cycle, itself included, and can also reach 3. Vertex 3 reaches nothing. So rows 0, 1, and 2 of the closure should be all True, and row 3 should be all False.
Implementation with a Boolean Matrix
def transitive_closure(n, edges):
# n vertices numbered 0..n-1; edges is a list of (u, v) pairs
reach = [[False] * n for _ in range(n)]
for u, v in edges:
reach[u][v] = True
for k in range(n):
for i in range(n):
if not reach[i][k]:
continue # i cannot reach k, so k cannot help i
row_k = reach[k]
row_i = reach[i]
for j in range(n):
if row_k[j]:
row_i[j] = True
return reach
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
reach = transitive_closure(4, edges)
for row in reach:
print([int(x) for x in row])
# [1, 1, 1, 1]
# [1, 1, 1, 1]
# [1, 1, 1, 1]
# [0, 0, 0, 0]
on_cycle = [i for i in range(4) if reach[i][i]]
print(on_cycle) # [0, 1, 2]The continue mirrors the dist[i][k] == math.inf skip in the Floyd-Warshall code. When i cannot reach k, nothing in row i can change during stage k.
Updating in place is safe here for the same reason it is safe in Floyd-Warshall. During stage k, row k and column k never change. For row k, the update is reach[k][j] |= reach[k][k] and reach[k][j], which cannot turn on a bit that was not already on. Column k behaves the same way. Every read of reach[i][k] or reach[k][j] therefore sees a stable value.
Faster in Practice: Rows as Bitsets
The inner loop says: "if i reaches k, then i also reaches everything k reaches." That is a single bitwise OR of two rows. If you store each row as an integer whose bit j means "reaches j," the whole j loop turns into one machine-level operation per word. On fixed-width hardware this gives O(V³ / w) time, where w is the word size (often 64). Python's arbitrary-size integers give you this speedup with very little code:
def transitive_closure_bits(n, edges):
rows = [0] * n # bit j of rows[i] is set when i reaches j
for u, v in edges:
rows[u] |= 1 << v
for k in range(n):
bit_k = 1 << k
row_k = rows[k]
for i in range(n):
if rows[i] & bit_k:
rows[i] |= row_k
return rows
edges = [(0, 1), (1, 2), (2, 0), (2, 3)]
rows = transitive_closure_bits(4, edges)
for i in range(4):
# Reverse the binary string so position j reads left to right
print(format(rows[i], '04b')[::-1])
# 1111
# 1111
# 1111
# 0000For a few thousand vertices, this version often runs orders of magnitude faster than the list-of-lists version in Python, because the inner work moves from interpreted code into the integer library.
When Not to Use Warshall
O(V³) does not depend on the number of edges. On a sparse graph, it is often cheaper to run a BFS or DFS from every vertex:
| Method | Time | Good fit |
|---|---|---|
| Warshall (boolean matrix) | O(V³) | Dense graphs, small V, simple code |
| Warshall with bitsets | O(V³ / w) | Dense graphs up to tens of thousands of vertices |
| BFS/DFS from each vertex | O(V · (V + E)) | Sparse graphs, where E is close to V |
| SCC condensation, then a DAG pass | O(V + E) plus the closure of the smaller DAG | Graphs with large strongly connected components |
| Single BFS/DFS | O(V + E) | You only need reachability from one source |
Some other points to keep in mind:
- The output is Θ(V²) no matter what. If V is in the millions, storing the full closure is not practical. Answer queries on demand instead, or use a reachability index.
- Undirected graphs need none of this. Reachability there is just "same connected component," which union-find or a single traversal computes in near-linear time.
- Self-loops set
reach[u][u] = Trueduring initialization. Under the strict convention that is correct, because a self-loop is a cycle of length 1. - Updates: adding one edge u → v can be handled incrementally. Every vertex that reaches u, or is u, now reaches everything v reaches, plus v. With bitsets that costs O(V²/w). Deleting an edge is much harder, and usually means recomputing.
Exercise
Run Warshall's algorithm by hand on the graph with edges 0 → 1 and 1 → 0 (n = 2), using the strict convention. What is the final matrix, and after which stage does reach[0][0] first become True?
Show answer
The initial matrix is [[F, T], [T, F]]. In stage k = 0, reach[1][0] and reach[0][1] are both True, so reach[1][1] becomes True. reach[0][0] stays False because it would need reach[0][0] and reach[0][0]. In stage k = 1, reach[0][1] and reach[1][0] are both True, so reach[0][0] becomes True. The final matrix is all True, and reach[0][0] first becomes True in stage k = 1.
Exercise
A graph has 100,000 vertices and 300,000 edges, and you need to answer about 50 reachability queries, each with a different source. Should you use Warshall's algorithm? Justify your answer with rough operation counts.
Show answer
No. Warshall takes about V³ = 10^15 steps (about 1.6 × 10^13 even with 64-bit bitsets), and the output matrix alone has 10^10 entries. Running one BFS per query costs about 50 × (V + E) = 50 × 400,000 = 2 × 10^7 steps and needs only O(V + E) memory.
Exercise
Modify transitiveclosurebits so that it returns the reflexive closure instead of the strict one, without changing the main triple loop.
Show answer
After the loop, set each vertex's own bit: for i in range(n): rows[i] |= 1 << i. Setting these bits before the loop would also give the same final result, but doing it afterward keeps the strict result available if you need it first.