Strongly Connected Components: Kosaraju's Algorithm
In a directed graph, two vertices and are strongly connected if each can reach the other: there is a path from to and a path from to . 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 time.
The component graph is a DAG
Contract each SCC to a single vertex and keep one edge from component to component whenever some edge of goes from a vertex of to a vertex of . The result is the component graph , and it is always acyclic: if it had a cycle through and , every vertex of could reach every vertex of 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 , which has every edge reversed. and have exactly the same SCCs, since reversing all edges reverses all paths. With adjacency lists, is built in time (representations).
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 SCCWatching 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.
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, , lies in the source component of the component graph, which has edges only going out. In the reversed graph those edges point into , so the second search from cannot leave it. Then , the next unvisited vertex in the order, collects : its reversed edge to leads into a component that is already finished. Finally collects the sink component .
Why it works
The proof rests on one lemma about the first DFS. For a set of vertices , let be the latest finishing time in it.
Lemma. Let and be distinct SCCs, and suppose has an edge from to . Then .
Proof sketch
Let be the first vertex of that the first DFS discovers. If : at time all of is white, and has white paths to every vertex of (inside ) and of (through the edge into ). By the white-path theorem they all become descendants of and finish before it, so . If : all of becomes descendants of , so . No vertex of is reachable from (that would merge the components), so all of is still white when finishes, and every vertex of finishes later: .
Theorem. The trees of the second DFS are exactly the SCCs.
Proof sketch
Induction on the trees of the second search. The root of the next tree is the unvisited vertex with the largest finishing time, so its component has the largest among the components not yet output. In an edge leaving toward an unvisited component would be an edge of from into , and by the lemma , contradicting the choice of . So edges leaving in lead only into components already output, whose vertices are visited. The search from therefore visits exactly the vertices of : all of them because they are strongly connected (in 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 .
Checking on random graphs
The definition gives a slow but obviously correct check: compute the set of vertices reachable from every vertex, and put and together when each is in the other's set. The program compares Kosaraju with it on 300 random graphs.
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.
#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 always acyclic?
- Because has no cycles
- A cycle through two components would make all their vertices mutually reachable, merging them into one component
- Because the transpose removes cycles
- Because DFS deletes back edges
In Kosaraju's second pass, why are vertices taken in order of decreasing finishing time?
- To visit the largest component first
- So that each new root lies in a component with no reversed edges leading to unvisited components
- Because the transpose is sorted
- Any order works
Edge goes from SCC to a different SCC . What does the lemma say about finishing times of the first DFS?
- always
- Nothing in general