Sub topic 7
Kosaraju's Algorithm: Two Passes of DFS
This chapter assumes you know recursive depth-first search (DFS), DFS finish times, the transpose graph, and the condensation DAG from the earlier chapters. Here we turn those pieces into a working algorithm. The proof of why it works comes in the next chapter.
The idea in one paragraph
Kosaraju's algorithm runs DFS twice. The first pass on the original graph records each vertex when it finishes. The second pass runs on the transpose, starting from vertices in decreasing finish time. Each DFS tree in the second pass is exactly one strongly connected component (SCC).
The vertex that finishes last belongs to a "source" component of the condensation, meaning no other component has an edge into it. In the transpose, every edge leaving that component is reversed, so a DFS started there cannot escape the component. It collects exactly that component and stops.
The steps
- Run DFS over every vertex of the graph. Append each vertex to
orderwhen its DFS call returns. - Build the transpose
radjby reversing every edge. - Walk
orderfrom the end. For each vertex that has no label yet, run DFS onradjand give every vertex it reaches the current component number.
Implementation
def kosaraju(n, adj):
visited = [False] * n
order = []
def dfs1(u):
visited[u] = True
for v in adj[u]:
if not visited[v]:
dfs1(v)
order.append(u) # record u at its finish time
for u in range(n):
if not visited[u]:
dfs1(u)
radj = [[] for _ in range(n)]
for u in range(n):
for v in adj[u]:
radj[v].append(u)
comp = [-1] * n
def dfs2(u, c):
comp[u] = c
for v in radj[u]:
if comp[v] == -1:
dfs2(v, c)
c = 0
for u in reversed(order): # decreasing finish time
if comp[u] == -1:
dfs2(u, c)
c += 1
return comp
# SCCs: {0,1,2}, {3,4,5}, {6,7}
adj = [[1], [2], [0, 3], [4], [5], [3], [5, 7], [6]]
print(kosaraju(8, adj)) # [1, 1, 1, 2, 2, 2, 0, 0]Tracing the example
| Step | Result |
|---|---|
| Pass 1 finish order | 5, 4, 3, 2, 1, 0, 7, 6 |
| Pass 2 start order | 6, 7, 0, 1, 2, 3, 4, 5 |
| DFS from 6 on transpose | labels {6, 7} as component 0 |
| DFS from 0 on transpose | labels {0, 1, 2} as component 1 |
| DFS from 3 on transpose | labels {3, 4, 5} as component 2 |
When the DFS from 3 runs on the transpose, it sees edges back to 2 and 6. Both already have labels, so it ignores them and stays inside its component. The numbering also comes out in topological order of the condensation: components 0 and 1 both point to component 2.
Common errors
- Using increasing finish order. The second pass must go through
orderin reverse. Going forward starts in a sink component of the condensation, and that order does not give correct results in general. - Ordering by discovery time. The algorithm depends on finish times. Appending
uat the start ofdfs1breaks it. - Recursion depth. Python's default limit is about 1000 frames, so a long path graph will crash both passes. A later chapter shows how to write the passes iteratively.
Exercise
For the graph with edges 0→1, 1→2, 2→1, 2→3, suppose pass 1 starts at vertex 0. What is the finish order, and which components does pass 2 find, in what order?
Show answer
DFS visits 0, 1, 2, 3, so the finish order is 3, 2, 1, 0. Pass 2 starts at 0 on the transpose, where 0 has no incoming edges to follow, so it finds {0}. Next it starts at 1, which reaches 2 through the reversed edge 2→1, so it finds {1, 2}. Then 2 is already labeled. Last it starts at 3, which can only reach the labeled vertex 2, so it finds {3}. The labels are 0: {0}, 1: {1, 2}, 2: {3}, which is a topological order.
Exercise
Why does a DFS on the transpose, started from the vertex with the latest finish time, never leave that vertex's SCC?
Show answer
That vertex lies in a source component of the condensation, so no edges from other components point into it. In the transpose, those missing incoming edges would have become outgoing edges. So the component has no edges leaving it in the transpose, and the DFS stays inside.