Loading...
Partition a directed graph into maximal subsets where each pair of vertices is mutually reachable. Collapse each SCC to produce a condensation DAG enabling higher-level analyses (e.g., layering, DP across components).
1KOSARAJU(G=(V,E)):2 visited = { }3 order = []4 // 1st DFS: record finish order5 for v in V:6 if v not visited:7 DFS1(v)8 // transpose graph9 GT = transpose(G)10 visited = { }11 components = []12 // 2nd DFS on GT in reverse finish order13 for v in reverse(order):14 if v not visited:15 C = []16 DFS2(v, C)17 components.push(C)18 return components19 20DFS1(u):21 visited.add(u)22 for each (u->v) in Adj[u]:23 if v not visited:24 DFS1(v)25 order.push(u)26 27DFS2(u, C):28 visited.add(u); C.push(u)29 for each (u->v) in AdjT[u]:30 if v not visited:31 DFS2(v, C)
1TARJAN(G):2 index = 03 stack = []4 onStack = {}5 indices[v] = -1 for v6 low[v] = 07 components = []8 for v in V:9 if indices[v] == -1:10 STRONGCONNECT(v)11 return components12 13STRONGCONNECT(v):14 indices[v] = index; low[v] = index; index++15 stack.push(v); onStack.add(v)16 for (v->w) in Adj[v]:17 if indices[w] == -1:18 STRONGCONNECT(w)19 low[v] = min(low[v], low[w])20 else if w in onStack:21 low[v] = min(low[v], indices[w])22 if low[v] == indices[v]:23 // root of SCC24 component = []25 repeat:26 w = stack.pop(); onStack.remove(w)27 component.push(w)28 until w == v29 components.push(component)
All edges/vertices processed constant times; Tarjan avoids explicit transpose pass.