{"id":26411,"date":"2017-12-20T21:18:39","date_gmt":"2017-12-20T15:48:39","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26411"},"modified":"2017-12-20T21:18:39","modified_gmt":"2017-12-20T15:48:39","slug":"java-programming-check-graph-strongly-connected-set-1-kosaraju-using-dfs","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-check-graph-strongly-connected-set-1-kosaraju-using-dfs\/","title":{"rendered":"JAVA 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>JAVA PROGRAMMING<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to check if a given directed graph is strongly<br\/>\/\/ connected or not<br\/>import java.io.*;<br\/>import java.util.*;<br\/>import java.util.LinkedList;<br\/> <br\/>\/\/ This class represents a directed graph using adjacency<br\/>\/\/ list representation<br\/>class Graph<br\/>{<br\/>    private int V;   \/\/ No. of vertices<br\/>    private LinkedList&lt;Integer&gt; adj[]; \/\/Adjacency List<br\/> <br\/>    \/\/Constructor<br\/>    Graph(int v)<br\/>    {<br\/>        V = v;<br\/>        adj = new LinkedList[v];<br\/>        for (int i=0; i&lt;v; ++i)<br\/>            adj[i] = new LinkedList();<br\/>    }<br\/> <br\/>    \/\/Function to add an edge into the graph<br\/>    void addEdge(int v,int w) {  adj[v].add(w); }<br\/> <br\/>    \/\/ A recursive function to print DFS starting from v<br\/>    void DFSUtil(int v,Boolean visited[])<br\/>    {<br\/>        \/\/ Mark the current node as visited and print it<br\/>        visited[v] = true;<br\/> <br\/>        int n;<br\/> <br\/>        \/\/ Recur for all the vertices adjacent to this vertex<br\/>        Iterator&lt;Integer&gt; i = adj[v].iterator();<br\/>        while (i.hasNext())<br\/>        {<br\/>            n = i.next();<br\/>            if (!visited[n])<br\/>                DFSUtil(n,visited);<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ Function that returns transpose of this graph<br\/>    Graph getTranspose()<br\/>    {<br\/>        Graph g = new Graph(V);<br\/>        for (int v = 0; v &lt; V; v++)<br\/>        {<br\/>            \/\/ Recur for all the vertices adjacent to this vertex<br\/>            Iterator&lt;Integer&gt; i = adj[v].listIterator();<br\/>            while (i.hasNext())<br\/>                g.adj[i.next()].add(v);<br\/>        }<br\/>        return g;<br\/>    }<br\/> <br\/>    \/\/ The main function that returns true if graph is strongly<br\/>    \/\/ connected<br\/>    Boolean isSC()<br\/>    {<br\/>        \/\/ Step 1: Mark all the vertices as not visited<br\/>        \/\/ (For first DFS)<br\/>        Boolean visited[] = new Boolean[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&#039;t visit all vertices, then<br\/>        \/\/ 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<br\/>        \/\/ 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<br\/>        \/\/ first vertex. Staring Vertex must be same starting<br\/>        \/\/ 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\/>    public static void main(String args[])<br\/>    {<br\/>        \/\/ Create graphs given in the above diagrams<br\/>        Graph g1 = new Graph(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\/>        if (g1.isSC())<br\/>            System.out.println(&quot;Yes&quot;);<br\/>        else<br\/>            System.out.println(&quot;No&quot;);<br\/> <br\/>        Graph g2 = new Graph(4);<br\/>        g2.addEdge(0, 1);<br\/>        g2.addEdge(1, 2);<br\/>        g2.addEdge(2, 3);<br\/>        if (g2.isSC())<br\/>            System.out.println(&quot;Yes&quot;);<br\/>        else<br\/>            System.out.println(&quot;No&quot;);<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">\n<tbody>\n<tr>\n<td class=\"code\">\n<div class=\"container\">\n<div class=\"line number1 index0 alt2\"><code class=\"java comments\"><\/code><code class=\"java plain\"><\/code><\/div>\n<div class=\"line number123 index122 alt2\">\n<p>Output:<\/p>\n<pre>Yes\r\nNo<\/pre>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">JAVA programming-Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)<\/code><\/pre> <\/div>\n<\/div>\n<\/div>\n<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>JAVA programming-Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)-find out whether the graph is strongly connected or not<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1,78385,73906,2139],"tags":[78756,78755,78422,78754,78751,78750,78753,78752],"class_list":["post-26411","post","type-post","status-publish","format-standard","hentry","category-coding","category-connectivity","category-graph-algorithms","category-java","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\/26411","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=26411"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26411\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26411"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26411"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26411"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}