Here, I describe the Kosaraju-Sharir algorithm for finding the strongly connected components in a directed graph and provide its C++ implementation.
A directed graph is called strongly connected if there is a path from each vertex in the graph to every other vertex. The strongly connected components of a directed graph G are its maximal strongly connected subgraphs.
Kosaraju-Sharir algorithm requires two passes of DFS to find the SCC (strongly connected components) i.e., it finds the SCC in O(V + E).
These are the steps of the algorithm:
- Compute the reverse graph GR, such that there is an edge from u to v in GR if and only if there is an edge from v to u in the original graph G.
- Run DFS over GR and compute the order in which vertices finish expansion.
- Run DFS over G in the reverse of the order computed in step 2. All vertices that are discovered during the expansion of a vertex v belong in the same SCC as v.
Take a look at the C++ implementation.
For an application of SCC, view the 2-SAT problem.