Check if a graph is strongly connected - Set 1 (Kosaraju using DFS) in C++

C++Server Side ProgrammingProgramming

Suppose we have a graph. We have to check whether the graph is strongly connected or not using Kosaraju algorithm. A graph is said to be strongly connected, if any two vertices has path between them, then the graph is connected. An undirected graph is strongly connected graph.

Some undirected graph may be connected but not strongly connected. This is an example of strongly connected graph.

This is an example of connected, but not strongly connected graph.

Here we will see, how to check a graph is strongly connected or not using the following steps of Kosaraju algorithm.

Steps

  • Mark all nodes as not visited

  • Start DFS traversal from any arbitrary vertex u. If the DFS fails to visit all nodes, then return false.

  • Reverse all edges of the graph

  • Set all vertices as not visited nodes again

  • Start DFS traversal from that vertex u. If the DFS fails to visit all nodes, then return false. otherwise true.

Example

 Live Demo

#include <iostream>
#include <list>
#include <stack>
using namespace std;
class Graph {
   int V;
   list<int> *adj;
   void dfs(int v, bool visited[]);
   public:
   Graph(int V) {
      this->V = V;
      adj = new list<int>[V];
   }
   ~Graph() {
      delete [] adj;
   }
   void addEdge(int v, int w);
   bool isStronglyConnected();
   Graph reverseArc();
};
void Graph::dfs(int v, bool visited[]) {
   visited[v] = true;
   list<int>::iterator i;
   for (i = adj[v].begin(); i != adj[v].end(); ++i)
   if (!visited[*i])
      dfs(*i, visited);
}
Graph Graph::reverseArc() {
   Graph graph(V);
   for (int v = 0; v < V; v++) {
      list<int>::iterator i;
      for(i = adj[v].begin(); i != adj[v].end(); ++i)
      graph.adj[*i].push_back(v);
   }
   return graph;
}
void Graph::addEdge(int u, int v) {
   adj[u].push_back(v);
}
bool Graph::isStronglyConnected() {
   bool visited[V];
   for (int i = 0; i < V; i++)
   visited[i] = false;
   dfs(0, visited);
   for (int i = 0; i < V; i++)
   if (visited[i] == false)
      return false;
   Graph graph = reverseArc();
   for(int i = 0; i < V; i++)
   visited[i] = false;
   graph.dfs(0, visited);
   for (int i = 0; i < V; i++)
   if (visited[i] == false)
      return false;
   return true;
}
int main() {
   Graph graph(5);
   graph.addEdge(0, 1);
   graph.addEdge(1, 2);
   graph.addEdge(2, 3);
   graph.addEdge(3, 0);
   graph.addEdge(2, 4);
   graph.addEdge(4, 2);
   graph.isStronglyConnected()? cout << "This is strongly connected" : cout << "This is not strongly connected";
}

Output

This is strongly connected
raja
Published on 22-Oct-2019 08:29:09
Advertisements