Strong Connectivity |
The strong connectivity algorithm is used to determine if a directed graph is strongly connected. A directed graph is said to be strongly connected if there exists a directed path between every pair of vertices. The algorithm works by first performing a depth-first search (DFS) on the given graph to check if all nodes are visited. If not, the graph is not strongly connected and the algorithm returns false. Then, the algorithm constructs the reverse graph by reversing the direction of all edges and performs another DFS on the reverse graph to check if all nodes are visited. If not, the reverse graph is not strongly connected, and the algorithm returns false. If both the normal and reverse graph DFS visits all nodes, then the graph is strongly connected, and the algorithm returns true.
Time Complexity: O(n+m)
bool strong_connectivity(vector<vector<int>> graph) { // Checking if the Normal Graph DFS visits all nodes DFS(graph, 0); for (int i = 0; i < visited.size(); i++) { if (!visited.at(i)) { return false; } } // Checking if the Reversed Graph DFS visits all nodes // Forming the Reverse Graph vector<vector<int>> reverse_graph; reverse_graph.resize(graph.size()); for (int i = 0; i < graph.size(); i++) { int from = i; for (auto to : graph.at(from)) { reverse_graph.at(to).push_back(from); } } for (int i = 0; i < visited.size(); i++) { visited.at(i) = false; } DFS(reverse_graph, 0); for (int i = 0; i < visited.size(); i++) { if (!visited.at(i)) { return false; } } return true; }