Strongly Connected Components (Kosaraju)
Split a directed graph into strongly connected components — maximal groups where every vertex reaches every other.
Open on GeeksforGeeks ↗Intuition
Two DFS passes. The first records finish times on the original graph; the last vertex to finish must sit in a 'source' component. Reversing every edge preserves each component internally but flips the one-way links between them — so a DFS on the reversed graph, started in finish-time order, can no longer escape a component. Each tree it grows is exactly one SCC.
Approach
Pass 1 — order by finish time
Run DFS on the original graph, pushing each vertex onto a stack when it finishes. Later finishers belong to components that come earlier in the condensed DAG.
Reverse the graph
Build the transpose: every u → v becomes v → u. Mutual reachability inside a component is unaffected, but the edges connecting different components now point the other way.
Pass 2 — DFS in reverse finish order
Pop vertices off the stack; each unvisited one starts a DFS on the reversed graph whose reachable set is precisely its SCC — the reversal blocks it from leaking into neighbouring components.
Solution & live demo
Edge cases
Pass 2 finds one component containing everything.
Every vertex is its own component — V components.
Each piece contributes its own components; the outer loops cover all.