Kosaraju's Algorithm
Imagine a social network. Person A follows person B, but does B follow A back? A Strongly Connected Component (SCC) is a group where everyone can reach everyone else — a true mutual-follow clique.
Kosaraju's algorithm finds all such groups using exactly two DFS passes. It's elegant, easy to code, and runs in linear time.
The Big Idea: Reverse the Graph
Here's the core trick. Build the transposed graph G^T — take every directed edge and flip it. A→B becomes B→A.
The magic: SCCs in G and G^T are identical. If everyone in a group could reach each other before flipping, they still can after. Flipping edges doesn't break mutual reachability inside an SCC — it only changes how SCCs relate to each other.
Pass 1: DFS on the Original Graph
Run a full DFS on the original graph. Each time a vertex finishes (all its neighbors explored), push it onto a stack. The last vertex to finish sits on top.
Think of it like leaving a building — the last person to enter (going deepest into the graph) is the first to come out. The stack is ordered so that SCC "sources" (SCCs with no incoming edges from other SCCs) finish last and land on top.
Pass 2: DFS on the Reversed Graph in Stack Order
Now build G^T and pop vertices from the stack one by one. For each unvisited vertex, run DFS on G^T. Every vertex you reach belongs to the same SCC.
Why does this work? The stack order ensures we start each new group from the right place. Because we're on the reversed graph, we can't accidentally "escape" into a different SCC — we stay contained within one group at a time.
The Condensation DAG
After labeling all SCCs, collapse each one into a single node. Any edge that crossed between SCCs becomes an edge between super-nodes. The result is always a DAG (directed acyclic graph) — ready for topological sort — if two SCCs had a cycle between them, all their vertices would be mutually reachable, making them one SCC to begin with.