暗色背景中戴帽子与金链的老人
戴金链的老人 · 伦勃朗 / Wikimedia Commons

The transitive closure records every connection that can be made by following one or more directed edges. A relation matrix already records one-step connections. The computational problem is to discover the remaining connections without listing every possible walk.

This note uses the conventions in 1.4 Representing Relations: rows are sources, columns are targets, and matrix products are Boolean products. As in 1.5 Closures of Relations, R+R^+ denotes the transitive closure using positive-length walks; R∗=IA∪R+R^*=I_A\cup R^+ also includes zero-length walks.

1. Computing a Closure with Boolean Powers

Let A={v1,…,vn}A=\{v_1,\ldots,v_n\}, where n≥1n\ge1, and fix this ordering for both rows and columns. For M=MRM=M_R, the entry (M[ℓ])ij(M^{[\ell]})_{ij} is 1 exactly when there is a walk of exactly ℓ\ell edges from viv_i to vjv_j. The brackets distinguish a Boolean power from an ordinary arithmetic power.

On a set with nn elements, every positive-length reachable pair has a witness of length at most nn. For distinct endpoints, n−1n-1 suffices; a closed walk returning to its starting vertex may require nn. The finite reachability bound therefore gives

MR+=M∨M[2]∨⋯∨M[n].M_{R^+}=M\lor M^{[2]}\lor\cdots\lor M^{[n]}.

Here ∨\lor is entrywise OR. Merely computing M[n]M^{[n]} would test exactly nn steps and could lose connections attainable only at other lengths.

Algorithm: Accumulate Boolean powers. Keep the current power PP and the accumulated reachability matrix BB:

procedure closure_by_powers(M: n by n zero-one matrix)
    P := copy of M
    B := copy of M
    for ell := 2 to n
        P := P Boolean-product M
        B := B entrywise-OR P
    return B

After iteration ℓ\ell, P=M[ℓ]P=M^{[\ell]} and B=M∨⋯∨M[ℓ]B=M\lor\cdots\lor M^{[\ell]}. Thus the returned matrix represents R+R^+. For n=1n=1, the loop is empty and the input itself is already the transitive closure.

With the usual dense Boolean multiplication, each product examines nn intermediate indices for each of n2n^2 entries, costing Θ(n3)\Theta(n^3) Boolean operations. Performing n−1n-1 such products gives Θ(n4)\Theta(n^4) time overall. The algorithm is correct, but it repeatedly solves many overlapping reachability problems.

Warshall’s algorithm changes the organizing question. Rather than increasing the allowed walk length, it increases the set of vertices allowed inside a walk.

2. Warshall’s Recurrence

Allowed Interior Vertices

An interior vertex is any occurrence of a vertex between the first and last positions of a walk. A directed walk may repeat vertices and edges. The endpoints need not belong to the allowed set of interior vertices.

Define W(k)=[wij(k)]W^{(k)}=[w_{ij}^{(k)}] by

wij(k)=1  ⟺  there is a positive-length walk from vi to vjwhose interior vertices all lie in {v1,…,vk}.w_{ij}^{(k)}=1 \iff \begin{gathered} \text{there is a positive-length walk from }v_i\text{ to }v_j\\ \text{whose interior vertices all lie in }\{v_1,\ldots,v_k\}. \end{gathered}

For k=0k=0, no interior vertex is allowed. A one-edge walk has no interior vertices, including a loop that is already present. Hence

W(0)=MR.W^{(0)}=M_R.

At k=nk=n, every vertex is allowed in the interior, so W(n)=MR+W^{(n)}=M_{R^+}. The superscript kk counts allowed interior vertices, not edges in a walk.

Keeping an Existing Connection or Going through a New Vertex

At stage kk, a connection from viv_i to vjv_j can already exist without using vkv_k in its interior. Otherwise, it can be obtained by joining a connection from viv_i to vkv_k to one from vkv_k to vjv_j. The recurrence is

wij(k)=wij(k−1)∨(wik(k−1)∧wkj(k−1)).\boxed{ w_{ij}^{(k)}= w_{ij}^{(k-1)}\lor \left(w_{ik}^{(k-1)}\land w_{kj}^{(k-1)}\right). }

Original diagram of an existing walk whose interior vertices all precede v k

Figure 1. An existing walk remains valid: all its interior vertices are already among the first k minus one vertices.

Original diagram of two subwalks joined at the newly allowed vertex v k

Figure 2. The two subwalks meet at the newly permitted interior vertex. Each subwalk uses only earlier interior vertices, which explains the AND term in the recurrence.

Why the recurrence is correct. If the first term is 1, its witness remains valid when the allowed set grows. If both entries in the second term are 1, concatenate their positive-length witness walks at vkv_k. Their interior vertices were already allowed, and the join adds the newly permitted vertex vkv_k. Thus every 1 produced by the recurrence represents a valid walk.

Conversely, suppose there is an allowed positive-length walk from viv_i to vjv_j, and choose a shortest such walk. Repeated portions can be removed, so an interior occurrence of vkv_k is needed at most once. For equal endpoints, retain a shortest positive closed walk rather than deleting the whole walk to length zero. If vkv_k does not occur in the interior, the first term is 1. If it does, split the walk at that occurrence. Both pieces have positive length and use only earlier interior vertices, so the second term is 1. This proves that the recurrence finds every permitted connection.

Starting with W(0)=MRW^{(0)}=M_R, induction on kk establishes the stated meaning of every stage. At the final stage, the matrix records all positive-length reachability and therefore represents the transitive closure.

Implementation and Complexity

The recurrence can be implemented with one mutable matrix:

procedure Warshall(M: n by n zero-one matrix)
    W := copy of M
    for k := 1 to n
        for i := 1 to n
            for j := 1 to n
                W[i,j] := W[i,j] OR (W[i,k] AND W[k,j])
    return W

Keep kk as the outermost loop. Each complete phase must permit one new intermediate vertex before the next phase begins. The loops over ii and jj may be interchanged.

In-place updates preserve the recurrence because row kk and column kk do not change during phase kk. For example, a row-kk update has the form

wkj←wkj∨(wkk∧wkj)=wkj.w_{kj}\leftarrow w_{kj}\lor(w_{kk}\land w_{kj})=w_{kj}.

The corresponding column-kk identity is the same. Consequently, each update reads the phase’s original wikw_{ik} and wkjw_{kj} even though other entries may already have changed.

The same recurrence gives a conditional row update. For fixed kk and ii, if wik=0w_{ik}=0, every entry in row ii stays the same. If wik=1w_{ik}=1, replace row ii by its entrywise OR with row kk. Row and column kk remain stable during the phase, so each test and row update uses the same values as the entrywise recurrence. Skipping rows can save work when many wikw_{ik} entries are zero. The worst-case time is still Θ(n3)\Theta(n^3) for scalar row updates.

There are n3n^3 updates, each using one AND and one OR. Under the Boolean-operation cost model, the time is Θ(n3)\Theta(n^3). The matrix uses Θ(n2)\Theta(n^2) storage, with O(1)O(1) additional working storage if the input may be overwritten. Copying the input preserves it at the cost of one additional n×nn\times n matrix.

MethodWhat grows between stagesTime with standard dense operations
Successive Boolean powersMaximum walk length included in the unionΘ(n4)\Theta(n^4)
WarshallSet of vertices allowed in the interiorΘ(n3)\Theta(n^3)

3. A Complete Matrix Trace

Example: A two-vertex cycle followed by a chain. Let

A={1,2,3,4},R={(1,2),(2,1),(2,3),(3,4)}.A=\{1,2,3,4\},\qquad R=\{(1,2),(2,1),(2,3),(3,4)\}.

Use the ordering 1,2,3,41,2,3,4 for rows and columns. Run Warshall’s algorithm and find W(0),W(1),…,W(4)W^{(0)},W^{(1)},\ldots,W^{(4)}. At each phase, list the newly added ordered pairs. Give R+R^+ and explain which diagonal entries become 1.

Show every phase and its new connections

Initial matrix. Only the four given edges are present:

W(0)=[0100101000010000].W^{(0)}= \begin{bmatrix} 0&1&0&0\\ 1&0&1&0\\ 0&0&0&1\\ 0&0&0&0 \end{bmatrix}.

Phase k=1k=1. Vertex 1 may now occur in the interior. The walk 2→1→22\to1\to2 adds (2,2)(2,2):

W(1)=[0100111000010000].W^{(1)}= \begin{bmatrix} 0&1&0&0\\ 1&1&1&0\\ 0&0&0&1\\ 0&0&0&0 \end{bmatrix}.

Phase k=2k=2. Vertices 1 and 2 are now allowed in the interior. Going through 2 adds (1,1)(1,1) from 1→2→11\to2\to1 and (1,3)(1,3) from 1→2→31\to2\to3:

W(2)=[1110111000010000].W^{(2)}= \begin{bmatrix} 1&1&1&0\\ 1&1&1&0\\ 0&0&0&1\\ 0&0&0&0 \end{bmatrix}.

For example, the (1,3)(1,3) update is

w13(2)=w13(1)∨(w12(1)∧w23(1))=0∨(1∧1)=1.w_{13}^{(2)}=w_{13}^{(1)}\lor \left(w_{12}^{(1)}\land w_{23}^{(1)}\right) =0\lor(1\land1)=1.

Phase k=3k=3. Going through 3 adds (1,4)(1,4) and (2,4)(2,4). The first uses an already discovered connection 1⇝31\leadsto3, followed by the original edge 3→43\to4:

W(3)=[1111111100010000].W^{(3)}= \begin{bmatrix} 1&1&1&1\\ 1&1&1&1\\ 0&0&0&1\\ 0&0&0&0 \end{bmatrix}.

Phase k=4k=4. Row 4 is all zeros, so no connection can continue from 4. The AND term cannot add any entry, and

W(4)=W(3)=[1111111100010000].W^{(4)}=W^{(3)}= \begin{bmatrix} 1&1&1&1\\ 1&1&1&1\\ 0&0&0&1\\ 0&0&0&0 \end{bmatrix}.

The newly added pairs are summarized below. Existing pairs remain present at every stage.

PhaseNewly permitted interior vertexNewly added pairs
11(2,2)(2,2)
22(1,1),(1,3)(1,1),(1,3)
33(1,4),(2,4)(1,4),(2,4)
44None

Reading the final matrix gives

R+={(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4),(3,4)}.\begin{aligned} R^+=\{&(1,1),(1,2),(1,3),(1,4),\\ &(2,1),(2,2),(2,3),(2,4),(3,4)\}. \end{aligned}

The cycle 1→2→11\to2\to1 gives positive-length returns to 1 and 2, so their diagonal entries become 1. Vertex 3 has no way back from 4, and vertex 4 has no outgoing edge. Their diagonal entries remain 0. The algorithm has computed a transitive relation, which need not be reflexive.

4. Diagonal Entries and Self-Check

Positive-Length Reachability versus Zero-Length Reachability

Initialization determines which closure is computed:

Initial matrixMeaning of the final matrix
MRM_RR+R^+: reachability by one or more edges
In∨MRI_n\lor M_RR∗=IA∪R+R^*=I_A\cup R^+: reachability by zero or more edges

For R+R^+, a final diagonal 1 means that a positive-length closed walk exists at that vertex. It must be justified by an original loop or a longer return route. For R∗R^*, every diagonal entry is 1 from the beginning because a zero-length walk stays at its starting vertex.

Neither result counts walks or gives their lengths. A 1 records existence only. In particular, the stage at which an entry appears does not give the shortest walk length: stage kk concerns the largest permitted interior-vertex index.

Review Problems

  1. On A={1,2,3}A=\{1,2,3\}, let R={(1,2),(2,3),(3,1)}R=\{(1,2),(2,3),(3,1)\}. Find R+R^+ and explain why all its diagonal entries are 1 even though RR has no loops. Would R∪R2R\cup R^2 be enough?
  2. On A={1,2,3}A=\{1,2,3\}, let S={(1,2),(2,3)}S=\{(1,2),(2,3)\}. Find S+S^+ and S∗S^*. Which diagonal entries should Warshall produce when initialized with MSM_S?
  3. Suppose that before phase k=3k=3, the entries w14=0w_{14}=0, w13=1w_{13}=1, and w34=1w_{34}=1. What is the new value of w14w_{14}, and what does this say about a walk from 1 to 4? Does it specify that walk’s exact length?
Show self-check answers
  1. Following the directed cycle reaches every vertex from every starting vertex. Thus R+=A×AR^+=A\times A, whose matrix is all 1s. Each return to its starting vertex takes three edges, so the diagonal pairs first occur in R3R^3. The union R∪R2R\cup R^2 lacks all three diagonal pairs and is insufficient. This illustrates why the general positive-length bound is nn, rather than n−1n-1.
  2. S+={(1,2),(2,3),(1,3)}S^+=\{(1,2),(2,3),(1,3)\}. There is no positive-length return to any vertex, so every diagonal entry stays 0 when initialized with MSM_S. The reflexive transitive closure is S∗=S+∪{(1,1),(2,2),(3,3)}S^*=S^+\cup\{(1,1),(2,2),(3,3)\}.
  3. The update gives 0∨(1∧1)=10\lor(1\land1)=1. Concatenating the known walk from 1 to 3 with the known walk from 3 to 4 proves positive-length reachability from 1 to 4, using only the permitted interior vertices. The entries do not record exact lengths, so the calculation alone does not supply one.

Glossary and Sources

TermMain idea
Transitive closure R+R^+Every pair connected by a positive-length directed walk
Reflexive transitive closure R∗R^*IA∪R+I_A\cup R^+, also admitting zero-length walks
Interior vertexAn occurrence between the first and last positions of a walk
Warshall phase kkPermit vkv_k in addition to the previously allowed interior vertices
In-place updateReuse one matrix while preserving the recurrence’s required values
  • Course slides.
  • The complete Warshall trace, implementation explanation, and self-checks are derived from the stated recurrence and definitions. Figures 1 and 2 are extracted from course slides and illustrate the two terms of that recurrence.

Updated:

RelationsClosuresMatricesAlgorithms