I need to check if a directed graph is strongly connected, or, in other words, if all nodes can be reached by any other node (not necessarily through direct edge).
One way of doing this is running a DFS and BFS on every node and see all others are still reachable.
Is there a better approach to do that?
A directed graph is called strongly connected if there is a path in each direction between each pair of vertices of the graph. That is, a path exists from the first vertex in the pair to the second, and another path exists from the second vertex to the first.
A simple idea is to use a all pair shortest path algorithm like Floyd Warshall or find Transitive Closure of graph. Time complexity of this method would be O(v3). We can also do DFS V times starting from every vertex. If any DFS, doesn't visit all vertices, then graph is not strongly connected.
Tarjan's strongly connected components algorithm is an algorithm in graph theory for finding the strongly connected components (SCCs) of a directed graph. It runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm.
We can use a traversal algorithm, either depth-first or breadth-first, to find the connected components of an undirected graph. If we do a traversal starting from a vertex v, then we will visit all the vertices that can be reached from v. These are the vertices in the connected component that contains v.
Consider the following algorithm.
Start at a random vertex v
of the graph G
, and run a DFS(G, v)
.
If DFS(G, v)
fails to reach every other vertex in the graph G
, then there is some vertex u
, such that there is no directed path from v
to u
, and thus G
is not strongly connected.
If it does reach every vertex, then there is a directed path from v
to every other vertex in the graph G
.
Reverse the direction of all edges in the directed graph G
.
Again run a DFS
starting at v
.
If the DFS fails to reach every vertex, then there is some vertex u
, such that in the original graph there is no directed path from u
to v
.
On the other hand, if it does reach every vertex, then in the original graph there is a directed path from every vertex u
to v
.
Thus, if G "passes" both DFSs, it is strongly connected. Furthermore, since a DFS runs in O(n + m)
time, this algorithm runs in O(2(n + m)) = O(n + m)
time, since it requires 2 DFS traversals.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With