Sub topic 12
Strongly Connected Components with Kosaraju's Algorithm
This chapter assumes you know the definition of a strongly connected component (SCC) from the chapter on directed connectivity. It also assumes you can read iterative depth-first search (DFS) with an explicit stack and are comfortable with O(V + E) analysis.
An SCC is a maximal set of vertices where every vertex can reach every other one by following edge directions. A single BFS or DFS from one vertex is not enough to find SCCs. The vertices it reaches include its own SCC plus everything downstream. Kosaraju's algorithm solves this with two DFS passes and a reversed copy of the graph.
The Two-Pass Idea
- Run DFS over the original graph. Record each vertex when it finishes, meaning all of its outgoing edges have been explored.
- Build the reversed graph, with every edge
u -> vturned intov -> u. - Take vertices in reverse finish order. Each unlabeled vertex starts a traversal of the reversed graph, and every vertex that traversal reaches forms one SCC.
Why Reversal Works
Shrink each SCC to a single node. The result is a directed acyclic graph called the condensation. The vertex that finishes last in pass one always lies in a source SCC of the condensation, which is a component with no incoming edges from other components. In the example, that vertex is 0, inside {0, 1, 2}.
Reversing the graph turns that source component into a sink, a component with no outgoing edges to other components. A traversal of the reversed graph that starts there cannot leave its own SCC, so it collects exactly that component. The next unlabeled vertex in reverse finish order lies in a source among the components that remain. Its reversed traversal can only reach components that are already labeled, and those are skipped. The same argument holds at every step.
Implementation
def kosaraju_scc(n, edges):
adj = [[] for _ in range(n)]
radj = [[] for _ in range(n)]
for u, v in edges:
adj[u].append(v)
radj[v].append(u)
visited = [False] * n
order = []
for s in range(n):
if visited[s]:
continue
visited[s] = True
stack = [(s, 0)]
while stack:
u, i = stack[-1]
if i < len(adj[u]):
stack[-1] = (u, i + 1)
v = adj[u][i]
if not visited[v]:
visited[v] = True
stack.append((v, 0))
else:
stack.pop()
order.append(u)
comp = [-1] * n
count = 0
for s in reversed(order):
if comp[s] != -1:
continue
comp[s] = count
stack = [s]
while stack:
u = stack.pop()
for v in radj[u]:
if comp[v] == -1:
comp[v] = count
stack.append(v)
count += 1
return count, comp
edges = [(0, 1), (1, 2), (2, 0), (2, 3), (3, 4), (4, 3)]
print(kosaraju_scc(5, edges))
# (2, [0, 0, 0, 1, 1])In pass one, each stack entry is a pair (vertex, next_edge_index). A vertex is appended to order only after its last edge has been examined, which gives true finish order. The second pass has no ordering requirement, so it uses the simpler push-all-neighbors stack from the earlier DFS labeling chapter.
Common Errors
| Mistake | Symptom |
|---|---|
| Second pass on the original graph instead of the reversed one | Downstream components get merged into one SCC |
| Processing `order` forward instead of reversed | Traversals start in sink components and leak into others |
| Recording discovery time instead of finish time | Wrong labels on graphs with cross edges |
| Forgetting to build `radj` alongside `adj` | Empty second pass; every vertex becomes its own SCC |
Cost
Each pass visits every vertex once and every edge once, so the time is O(V + E). Space is O(V + E) because the graph is stored twice, plus O(V) for visited, order, comp, and the stack. Storing the graph twice is the main practical drawback. Tarjan's algorithm, covered next, avoids it.
Exercise
For the edges (0,1), (1,0), (1,2), (2,3), (3,2), (3,4) on 5 vertices, list the SCCs. Then explain what goes wrong if the second pass runs on the original graph in reverse finish order.
Show answer
The SCCs are {0, 1}, {2, 3}, and {4}. Pass one starting at 0 finishes 4 first and 0 last, so the second pass starts at 0. On the reversed graph, 0 reaches only 1, which is correct. On the original graph, 0 reaches 1, 2, 3, and 4, so all five vertices would be wrongly labeled as one component.
Exercise
Why is it safe for the second pass to use a stack that does not track finish order?
Show answer
The second pass only needs the set of vertices reachable from the start vertex in the reversed graph. Any traversal order gives the same reachable set, so plain DFS or BFS both work.