Kosaraju's Two-Pass Algorithm
Kosaraju's Two-Pass Algorithm
Kosaraju's Two-Pass Algorithm
Algorithm
11
13
15
def kosaraju ( G ) :
S = stack ()
G_rev = reverse ( G )
# Pass 1
for v in G_rev :
if v unexplored :
explore ( v )
DFS_pass1 ( G_rev , v , S )
# Pass 2
while not empty ( S ) :
v = S . pop ()
if v explored : # Flipped after pass 1
unexplore ( v )
SCC rooted at S = DFS_pass2 (G , v )
17
19
21
23
25
27
29
31
Essentially, the algorithm sorts the vertices in the graph by DFS finishing time and then iterates backwards through them to conduct one more
DFS to uncover the SCCs. The second pass only explores sink nodes of
a respective SCC.
Analysis/Correctness
The SCCs of G themselves introduce a meta-DAG, in that if they are collapsed into nodes and the paths between then are maintained, the resulting
graph is also a DAG.
Key Lemma
c1
c2
If f (v) is the position on the stack of node v, with higher values corresponding to positions towards the top of the stack, then:
max f (v) < max f (w)
vc1
(1)
wc2
f1
f4
f3