{"id":26363,"date":"2017-12-20T21:16:31","date_gmt":"2017-12-20T15:46:31","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26363"},"modified":"2017-12-20T21:16:31","modified_gmt":"2017-12-20T15:46:31","slug":"c-programming-check-if-a-graph-is-strongly-connected","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-check-if-a-graph-is-strongly-connected\/","title":{"rendered":"C programming &#8211; Check if a graph is strongly connected"},"content":{"rendered":"<p>Given a directed graph,find out whether the graph is strongly connected or not. A directed graph is strongly connected if<span id=\"more-118510\"><\/span> there is a path between any two pair of vertices. For example, following is a strongly connected graph.<\/p>\n<p><strong>It is easy for undirected graph<\/strong>, we can just do a BFS and DFS starting from any vertex. If BFS or DFS visits all vertices, then the given undirected graph is connected. This approach won\u2019t work for a directed graph. For example, consider the following graph which is not strongly connected. If we start DFS (or BFS) from vertex 0, we can reach all vertices, but if we start from any other vertex, we cannot reach all vertices.<\/p>\n<p><strong>How to do for directed graph?<\/strong><br \/>\nA simple idea is to use a all pair shortest path algorithm like <strong><a href=\"http:\/\/www.geeksforgeeks.org\/dynamic-programming-set-16-floyd-warshall-algorithm\/\" target=\"_blank\" rel=\"noopener noreferrer\">Floyd Warshall<\/a> or find <a href=\"http:\/\/www.geeksforgeeks.org\/transitive-closure-of-a-graph\/\" target=\"_blank\" rel=\"noopener noreferrer\">Transitive Closure<\/a><\/strong> of graph. Time complexity of this method would be O(v<sup>3<\/sup>).<\/p>\n<p>We can also <strong>do <a href=\"http:\/\/www.geeksforgeeks.org\/depth-first-traversal-for-a-graph\/\" target=\"_blank\" rel=\"noopener noreferrer\">DFS <\/a>V times<\/strong> starting from every vertex. If any DFS, doesn\u2019t visit all vertices, then graph is not strongly connected. This algorithm takes O(V*(V+E)) time which can be same as transitive closure for a dense graph.<\/p>\n<p>A better idea can be <strong><a href=\"http:\/\/www.geeksforgeeks.org\/strongly-connected-components\/\" target=\"_blank\" rel=\"noopener\">Strongly Connected Components (SCC)<\/a> algorithm<\/strong>. We can find all SCCs in O(V+E) time. If number of SCCs is one, then graph is strongly connected. The algorithm for SCC does extra work as it finds all SCCs.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>Following is <strong>Kosaraju\u2019s DFS based simple algorithm that does two DFS traversals<\/strong> of graph:<br \/>\n<strong>1)<\/strong> Initialize all vertices as not visited.<\/p>\n<p><strong>2)<\/strong> Do a DFS traversal of graph starting from any arbitrary vertex v. If DFS traversal doesn\u2019t visit all vertices, then return false.<\/p>\n<p><strong>3)<\/strong> Reverse all arcs (or find transpose or reverse of graph)<\/p>\n<p><strong>4)<\/strong> Mark all vertices as not-visited in reversed graph.<\/p>\n<p><strong>5)<\/strong> Do a DFS traversal of reversed graph starting from same vertex v (Same as step 2). If DFS traversal doesn\u2019t visit all vertices, then return false. Otherwise return true.<\/p>\n<p>The idea is, if every node can be reached from a vertex v, and every node can reach v, then the graph is strongly connected. In step 2, we check if all vertices are reachable from v. In step 4, we check if all vertices can reach v (In reversed graph, if all vertices are reachable from v, then all vertices can reach v in original graph).<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>C++ PROGRAMMING<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-cpp code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-cpp code-embed-code\">\/\/ C++ program to check if a given directed graph is strongly <br\/>\/\/ connected or not<br\/>#include &lt;iostream&gt;<br\/>#include &lt;list&gt;<br\/>#include &lt;stack&gt;<br\/>using namespace std;<br\/> <br\/>class Graph<br\/>{<br\/>    int V;    \/\/ No. of vertices<br\/>    list&lt;int&gt; *adj;    \/\/ An array of adjacency lists<br\/> <br\/>    \/\/ A recursive function to print DFS starting from v<br\/>    void DFSUtil(int v, bool visited[]);<br\/>public:<br\/>    \/\/ Constructor and Destructor<br\/>    Graph(int V) { this-&gt;V = V;  adj = new list&lt;int&gt;[V];}<br\/>    ~Graph() { delete [] adj; }<br\/> <br\/>    \/\/ Method to add an edge<br\/>    void addEdge(int v, int w);<br\/> <br\/>    \/\/ The main function that returns true if the graph is strongly<br\/>    \/\/ connected, otherwise false<br\/>    bool isSC();<br\/> <br\/>    \/\/ Function that returns reverse (or transpose) of this graph<br\/>    Graph getTranspose();<br\/>};<br\/> <br\/>\/\/ A recursive function to print DFS starting from v<br\/>void Graph::DFSUtil(int v, bool visited[])<br\/>{<br\/>    \/\/ Mark the current node as visited and print it<br\/>    visited[v] = true;<br\/> <br\/>    \/\/ Recur for all the vertices adjacent to this vertex<br\/>    list&lt;int&gt;::iterator i;<br\/>    for (i = adj[v].begin(); i != adj[v].end(); ++i)<br\/>        if (!visited[*i])<br\/>            DFSUtil(*i, visited);<br\/>}<br\/> <br\/>\/\/ Function that returns reverse (or transpose) of this graph<br\/>Graph Graph::getTranspose()<br\/>{<br\/>    Graph g(V);<br\/>    for (int v = 0; v &lt; V; v++)<br\/>    {<br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        list&lt;int&gt;::iterator i;<br\/>        for(i = adj[v].begin(); i != adj[v].end(); ++i)<br\/>        {<br\/>            g.adj[*i].push_back(v);<br\/>        }<br\/>    }<br\/>    return g;<br\/>}<br\/> <br\/>void Graph::addEdge(int v, int w)<br\/>{<br\/>    adj[v].push_back(w); \/\/ Add w to v\u2019s list.<br\/>}<br\/> <br\/>\/\/ The main function that returns true if graph is strongly connected<br\/>bool Graph::isSC()<br\/>{<br\/>    \/\/ St1p 1: Mark all the vertices as not visited (For first DFS)<br\/>    bool visited[V];<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        visited[i] = false;<br\/> <br\/>    \/\/ Step 2: Do DFS traversal starting from first vertex.<br\/>    DFSUtil(0, visited);<br\/> <br\/>     \/\/ If DFS traversal doesn\u2019t visit all vertices, then return false.<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        if (visited[i] == false)<br\/>             return false;<br\/> <br\/>    \/\/ Step 3: Create a reversed graph<br\/>    Graph gr = getTranspose();<br\/> <br\/>    \/\/ Step 4: Mark all the vertices as not visited (For second DFS)<br\/>    for(int i = 0; i &lt; V; i++)<br\/>        visited[i] = false;<br\/> <br\/>    \/\/ Step 5: Do DFS for reversed graph starting from first vertex.<br\/>    \/\/ Staring Vertex must be same starting point of first DFS<br\/>    gr.DFSUtil(0, visited);<br\/> <br\/>    \/\/ If all vertices are not visited in second DFS, then<br\/>    \/\/ return false<br\/>    for (int i = 0; i &lt; V; i++)<br\/>        if (visited[i] == false)<br\/>             return false;<br\/> <br\/>    return true;<br\/>}<br\/> <br\/>\/\/ Driver program to test above functions<br\/>int main()<br\/>{<br\/>    \/\/ Create graphs given in the above diagrams<br\/>    Graph g1(5);<br\/>    g1.addEdge(0, 1);<br\/>    g1.addEdge(1, 2);<br\/>    g1.addEdge(2, 3);<br\/>    g1.addEdge(3, 0);<br\/>    g1.addEdge(2, 4);<br\/>    g1.addEdge(4, 2);<br\/>    g1.isSC()? cout &lt;&lt; &quot;Yes\\n&quot; : cout &lt;&lt; &quot;No\\n&quot;;<br\/> <br\/>    Graph g2(4);<br\/>    g2.addEdge(0, 1);<br\/>    g2.addEdge(1, 2);<br\/>    g2.addEdge(2, 3);<br\/>    g2.isSC()? cout &lt;&lt; &quot;Yes\\n&quot; : cout &lt;&lt; &quot;No\\n&quot;;<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<div class=\"line number1 index0 alt2\"><code class=\"cpp comments\"><\/code>Output:<\/div>\n<div class=\"line number121 index120 alt2\">\n<pre>Yes\r\nNo<\/pre>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">C programming-Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>C programming &#8211; Check if a graph is strongly connected &#8211; A directed graph is strongly connected if there is a path between any two pair of vertices<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69866,1,78385,73906],"tags":[78756,78755,78422,78754,78751,78750,78753,78752],"class_list":["post-26363","post","type-post","status-publish","format-standard","hentry","category-c-programming","category-coding","category-connectivity","category-graph-algorithms","tag-c-program-to-check-the-connectivity-of-undirected-graph-using-bfs","tag-check-if-graph-is-connected-adjacency-matrix","tag-check-if-path-exists-between-two-nodes","tag-check-if-undirected-graph-is-connected","tag-connected-graph-examples","tag-strongly-connected-graph-example","tag-strongly-connected-undirected-graph","tag-weakly-connected-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26363","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26363"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26363\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26363"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26363"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26363"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}