Skip to main content

Warshall's algorithm with example

Short answer

Warshall's algorithm computes transitive closure using triple nested loops: for each k, set P[i][j] = P[i][j] OR (P[i][k] AND P[k][j]). Example: directed edges 1→2, 2→3, 4→1 yield closure where 1 reaches 2,3; 2 reaches 3; 4 reaches 1,2,3.

Write an algorithm for Warshall's algorithm and illustrate with an example.

Warshall's algorithm finds the transitive closure of a directed graph, i.e. the matrix P where P[i][j] = 1 if there is a path from vertex i to vertex j. Start with the adjacency matrix and, for each vertex k in turn, allow k as an intermediate vertex: a path i → j exists if one already exists, or if i → k and k → j both exist.

WARSHALL(A, n)           // A = adjacency matrix (0/1)
1. P = A
2. for k = 1 to n
3.     for i = 1 to n
4.         for j = 1 to n
5.             P[i][j] = P[i][j] OR (P[i][k] AND P[k][j])
6. return P
void warshall(int p[][N], int n) {
    for (int k = 0; k < n; k++)
        for (int i = 0; i < n; i++)
            for (int j = 0; j < n; j++)
                p[i][j] = p[i][j] || (p[i][k] && p[k][j]);
}

Time O(n³), space O(n²). After step k, P[i][j] = 1 means a path exists using only vertices 1..k as intermediates.

Example

Directed graph with vertices 1, 2, 3, 4 and edges 1→2, 2→3, 4→1.

 4 -> 1 -> 2 -> 3

Rows and columns are ordered 1, 2, 3, 4.

MatrixRow 1Row 2Row 3Row 4Change
P₀ (adjacency)0 1 0 00 0 1 00 0 0 01 0 0 0initial
P₁ (via 1)0 1 0 00 0 1 00 0 0 01 1 0 04→1→2 gives 4→2
P₂ (via 2)0 1 1 00 0 1 00 0 0 01 1 1 01→2→3 gives 1→3; 4→2→3 gives 4→3
P₃ (via 3)0 1 1 00 0 1 00 0 0 01 1 1 0no change (3 has no outgoing edge)
P₄ (via 4)0 1 1 00 0 1 00 0 0 01 1 1 0no change (no edge enters 4)

Transitive closure: 1 reaches 2, 3; 2 reaches 3; 3 reaches none; 4 reaches 1, 2, 3.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 10 questions →