Problem Statement
Given a directed graph with V
nodes and E
edges, find, if any, its
Strongly Connected Components (SCC)
A SCC is defined as a sub-graph where for every pair of vertices u
and v
, there exists a path from u
to v
and from v
to u
.
Example: A communication network, where x
people continiously talk
to each other on the phone, can be an application of SCC.
An illustration of a graph with multiple SCCs can be found in this Wikipedia article.
Note: If a graph’s SCC are contracted (replaced by larger vertices), they form a DAG.
General Idea | \(O(V+E)\)
This problem can be solved using Tarjan’s strongly connected components algorithm.
The crutch of this algorithm is to use DFS
to produce a DFS
tree/forest.
Strongly connected components of the graph will form subtrees in the generated
DFS
Tree. We can then find the root of such subtrees and print all its nodes.
Similar to how we find articulation points and bridges,
we’ll keep track of two int
arrays, dfs_low[]
and dfs_num[]
. For a node u
,
if dfs_low[u] == dfs_num[u]
, u
is the the root of a subtree i.e u
and its children
form a strongly connected component.
To keep track of each node we visit in the DFS
tree, we use a stack result
.
result
will be used for figuring out which nodes belong u
’s subtree.
Code
C++11 code below.