TExcelTAD
Home › Graph Algorithms › Strongly Connected Components: Kosaraju's Algorithm

Strongly Connected Components: Kosaraju's Algorithm

In a directed graph, two vertices uu and vv are strongly connected if each can reach the other: there is a path from uu to vv and a path from vv to uu. This relation is an equivalence relation (reflexive, symmetric and transitive), so it splits the vertices into classes, the strongly connected components (SCCs). On the web they are clusters of pages that all link to each other; in a program's call graph they are groups of mutually recursive functions; in a package manager they are dependency loops that must be built together. Kosaraju's algorithm finds all of them with two depth-first searches, in Θ(V+E)\Theta(V + E) time.

The component graph is a DAG

Contract each SCC to a single vertex and keep one edge from component CC to component C′C' whenever some edge of GG goes from a vertex of CC to a vertex of C′C'. The result is the component graph GSCCG^{\text{SCC}}, and it is always acyclic: if it had a cycle through CC and C′C', every vertex of CC could reach every vertex of C′C' and back, so they would be one component. Every directed graph is therefore a DAG of strongly connected pieces.

Kosaraju's algorithm uses the transpose GTG^{\mathsf{T}}, which has every edge reversed. GG and GTG^{\mathsf{T}} have exactly the same SCCs, since reversing all edges reverses all paths. With adjacency lists, GTG^{\mathsf{T}} is built in Θ(V+E)\Theta(V + E) time (representations).

text
SCC(G)
1  run DFS(G) to compute the finishing time u.f of every vertex
2  build the transpose G^T
3  run DFS(G^T), but in the outer loop consider the vertices in order of decreasing u.f
4  output the vertices of each tree of the second depth-first forest as one SCC

Watching it work

The animation shows both passes. In pass 1 each vertex is labelled with its discovery and finishing times; in pass 2 each tree of the search in the reversed graph is coloured as one component.

python · try it yourself
adj = {"A": ["B"], "B": ["C", "D"], "C": ["A", "E"], "D": ["E"], "E": ["D", "F"], "F": ["G"], "G": ["H"], "H": ["F"]}

def kosaraju(adj):
    seen, finish = set(), []
    d, f, time = {}, {}, 0
    def visit1(u):
        nonlocal time
        seen.add(u); time += 1; d[u] = time
        for v in sorted(adj[u]):
            if v not in seen:
                visit1(v)
        time += 1; f[u] = time
        finish.append(u)
    for u in sorted(adj):
        if u not in seen:
            visit1(u)
    print("pass 1 times:", ", ".join(f"{u} {d[u]}/{f[u]}" for u in sorted(adj)))

    radj = {u: [] for u in adj}                  # the transpose
    for u in adj:
        for v in adj[u]:
            radj[v].append(u)
    order = finish[::-1]
    print("pass 2 order (decreasing finish):", " ".join(order))
    comp = {}
    def visit2(u, c):
        comp[u] = c
        for v in sorted(radj[u]):
            if v not in comp:
                visit2(v, c)
    components = []
    for u in order:
        if u not in comp:
            visit2(u, len(components))
            components.append(sorted(x for x in comp if comp[x] == len(components)))
    return components, comp

components, comp = kosaraju(adj)
for i, c in enumerate(components, 1):
    print(f"C{i}: {{{', '.join(c)}}}")
dag = sorted({(comp[u] + 1, comp[v] + 1) for u in adj for v in adj[u] if comp[u] != comp[v]})
print("component graph edges:", ", ".join(f"C{a}->C{b}" for a, b in dag))
pass 1 times: A 1/16, B 2/15, C 3/14, D 5/6, E 4/13, F 7/12, G 8/11, H 9/10
pass 2 order (decreasing finish): A B C E F G H D
C1: {A, B, C}
C2: {D, E}
C3: {F, G, H}
component graph edges: C1->C2, C2->C3

The latest finisher, AA, lies in the source component {A,B,C}\{A, B, C\} of the component graph, which has edges only going out. In the reversed graph those edges point into {A,B,C}\{A, B, C\}, so the second search from AA cannot leave it. Then EE, the next unvisited vertex in the order, collects {D,E}\{D, E\}: its reversed edge to CC leads into a component that is already finished. Finally FF collects the sink component {F,G,H}\{F, G, H\}.

Why it works

The proof rests on one lemma about the first DFS. For a set of vertices UU, let f(U)=max⁡u∈Uu.ff(U) = \max_{u \in U} u.f be the latest finishing time in it.

Lemma. Let CC and C′C' be distinct SCCs, and suppose GG has an edge from CC to C′C'. Then f(C)>f(C′)f(C) > f(C').

Proof sketch

Let xx be the first vertex of C∪C′C \cup C' that the first DFS discovers. If x∈Cx \in C: at time x.dx.d all of C∪C′C \cup C' is white, and xx has white paths to every vertex of CC (inside CC) and of C′C' (through the edge into C′C'). By the white-path theorem they all become descendants of xx and finish before it, so f(C)=x.f>f(C′)f(C) = x.f > f(C'). If x∈C′x \in C': all of C′C' becomes descendants of xx, so f(C′)=x.ff(C') = x.f. No vertex of CC is reachable from C′C' (that would merge the components), so all of CC is still white when xx finishes, and every vertex of CC finishes later: f(C)>f(C′)f(C) > f(C').

Theorem. The trees of the second DFS are exactly the SCCs.

Proof sketch

Induction on the trees of the second search. The root rr of the next tree is the unvisited vertex with the largest finishing time, so its component CC has the largest ff among the components not yet output. In GTG^{\mathsf{T}} an edge leaving CC toward an unvisited component C′C' would be an edge of GG from C′C' into CC, and by the lemma f(C′)>f(C)f(C') > f(C), contradicting the choice of rr. So edges leaving CC in GTG^{\mathsf{T}} lead only into components already output, whose vertices are visited. The search from rr therefore visits exactly the vertices of CC: all of them because they are strongly connected (in GTG^{\mathsf{T}} too), and nothing else because every exit is blocked.

Both passes are DFS, and building the transpose is linear, so the whole algorithm runs in Θ(V+E)\Theta(V + E).

Checking on random graphs

The definition gives a slow but obviously correct check: compute the set of vertices reachable from every vertex, and put uu and vv together when each is in the other's set. The program compares Kosaraju with it on 300 random graphs.

python · try it yourself
import random

def kosaraju(adj):
    n = len(adj)
    seen, finish = [False] * n, []
    def visit1(u):
        seen[u] = True
        for v in adj[u]:
            if not seen[v]:
                visit1(v)
        finish.append(u)
    for u in range(n):
        if not seen[u]:
            visit1(u)
    radj = [[] for _ in range(n)]
    for u in range(n):
        for v in adj[u]:
            radj[v].append(u)
    comp = [-1] * n
    def visit2(u, c):
        comp[u] = c
        for v in radj[u]:
            if comp[v] < 0:
                visit2(v, c)
    count = 0
    for u in reversed(finish):
        if comp[u] < 0:
            visit2(u, count)
            count += 1
    return comp, count

def brute(adj):
    n = len(adj)
    reach = []
    for s in range(n):
        seen, stack = {s}, [s]
        while stack:
            for v in adj[stack.pop()]:
                if v not in seen:
                    seen.add(v); stack.append(v)
        reach.append(seen)
    return {frozenset(v for v in range(n) if v in reach[u] and u in reach[v]) for u in range(n)}

rng = random.Random(17)
sizes = {}
for trial in range(300):
    n = rng.randint(1, 25)
    adj = [[v for v in range(n) if v != u and rng.random() < 0.08] for u in range(n)]
    comp, count = kosaraju(adj)
    groups = {frozenset(v for v in range(n) if comp[v] == c) for c in range(count)}
    assert groups == brute(adj)
    for g in groups:
        sizes[len(g)] = sizes.get(len(g), 0) + 1
print("Kosaraju matches mutual reachability on 300 random graphs")
print("component sizes found:", dict(sorted(sizes.items())))
Kosaraju matches mutual reachability on 300 random graphs
component sizes found: {1: 2602, 2: 76, 3: 22, 4: 12, 5: 9, 6: 10, 7: 6, 8: 10, 9: 4, 10: 3, 11: 5, 12: 7, 13: 3, 14: 5, 15: 7, 16: 4, 17: 5, 18: 3, 19: 3, 20: 1, 21: 2, 23: 1}

Sparse random digraphs consist mostly of singleton components with a few larger ones, the shape real networks often have too: one giant strongly connected core surrounded by many vertices that only lead into it or out of it. The practice problem Strongly Connected Components asks for the number of components.

In C++

The C++ version runs both passes with recursion and reports each component.

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

int main() {
    const std::string names = "ABCDEFGH";
    const int n = static_cast<int>(names.size());
    std::vector<std::vector<int>> adj = {{1}, {2, 3}, {0, 4}, {4}, {3, 5}, {6}, {7}, {5}};
    std::vector<std::vector<int>> radj(n);
    for (int u = 0; u < n; ++u)
        for (int v : adj[u]) radj[v].push_back(u);
    for (auto& list : radj) std::sort(list.begin(), list.end());

    std::vector<bool> seen(n, false);
    std::vector<int> finish, comp(n, -1);
    std::function<void(int)> visit1 = [&](int u) {
        seen[u] = true;
        for (int v : adj[u]) if (!seen[v]) visit1(v);
        finish.push_back(u);
    };
    for (int u = 0; u < n; ++u) if (!seen[u]) visit1(u);

    std::function<void(int, int)> visit2 = [&](int u, int c) {
        comp[u] = c;
        for (int v : radj[u]) if (comp[v] < 0) visit2(v, c);
    };
    int count = 0;
    for (auto it = finish.rbegin(); it != finish.rend(); ++it)
        if (comp[*it] < 0) visit2(*it, count++);
    for (int c = 0; c < count; ++c) {
        std::printf("C%d:", c + 1);
        for (int v = 0; v < n; ++v) if (comp[v] == c) std::printf(" %c", names[v]);
        std::printf("\n");
    }
}
C1: A B C
C2: D E
C3: F G H

Test yourself

Why is the component graph GSCCG^{\text{SCC}} always acyclic?

  1. Because GG has no cycles
  2. A cycle through two components would make all their vertices mutually reachable, merging them into one component
  3. Because the transpose removes cycles
  4. Because DFS deletes back edges

In Kosaraju's second pass, why are vertices taken in order of decreasing finishing time?

  1. To visit the largest component first
  2. So that each new root lies in a component with no reversed edges leading to unvisited components
  3. Because the transpose is sorted
  4. Any order works

Edge (u,v)(u, v) goes from SCC CC to a different SCC C′C'. What does the lemma say about finishing times of the first DFS?

  1. f(C)<f(C′)f(C) < f(C')
  2. f(C)>f(C′)f(C) > f(C')
  3. u.f<v.fu.f < v.f always
  4. Nothing in general