{"id":26434,"date":"2017-12-20T21:21:06","date_gmt":"2017-12-20T15:51:06","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26434"},"modified":"2017-12-20T21:21:06","modified_gmt":"2017-12-20T15:51:06","slug":"python-programming-check-graph-strongly-connected-set-1-kosaraju-using-dfs","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-check-graph-strongly-connected-set-1-kosaraju-using-dfs\/","title":{"rendered":"PYTHON programming-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><\/p>\n<p>A 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:<\/p>\n<p><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<p>PYTHON PROGRAMMING<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-python code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-python code-embed-code\"># Python program to check if a given directed graph is strongly <br\/># connected or not<br\/> <br\/>from collections import defaultdict<br\/>  <br\/>#This class represents a directed graph using adjacency list representation<br\/>class Graph:<br\/>  <br\/>    def __init__(self,vertices):<br\/>        self.V= vertices #No. of vertices<br\/>        self.graph = defaultdict(list) # default dictionary to store graph<br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v):<br\/>        self.graph[u].append(v)<br\/>     <br\/>  <br\/>    #A function used by isSC() to perform DFS<br\/>    def DFSUtil(self,v,visited):<br\/> <br\/>        # Mark the current node as visited <br\/>        visited[v]= True<br\/> <br\/>        #Recur for all the vertices adjacent to this vertex<br\/>        for i in self.graph[v]:<br\/>            if visited[i]==False:<br\/>                self.DFSUtil(i,visited)<br\/> <br\/> <br\/>    # Function that returns reverse (or transpose) of this graph<br\/>    def getTranspose(self):<br\/> <br\/>        g = Graph(self.V)<br\/> <br\/>        # Recur for all the vertices adjacent to this vertex<br\/>        for i in self.graph:<br\/>            for j in self.graph[i]:<br\/>                g.addEdge(j,i)<br\/>         <br\/>        return g<br\/> <br\/>         <br\/>    # The main function that returns true if graph is strongly connected<br\/>    def isSC(self):<br\/> <br\/>        # Step 1: Mark all the vertices as not visited (For first DFS)<br\/>        visited =[False]*(self.V)<br\/>         <br\/>        # Step 2: Do DFS traversal starting from first vertex.<br\/>        self.DFSUtil(0,visited)<br\/> <br\/>        # If DFS traversal doesnt visit all vertices, then return false<br\/>        if any(i == False for i in visited):<br\/>            return False<br\/> <br\/>        # Step 3: Create a reversed graph<br\/>        gr = self.getTranspose()<br\/>         <br\/>        # Step 4: Mark all the vertices as not visited (For second DFS)<br\/>        visited =[False]*(self.V)<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\/>        if any(i == False for i in visited):<br\/>            return False<br\/> <br\/>        return True<br\/> <br\/># Create a graph given in the above diagram<br\/>g1 = 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\/>print &quot;Yes&quot; if g1.isSC() else &quot;No&quot;<br\/> <br\/>g2 = Graph(4)<br\/>g2.addEdge(0, 1)<br\/>g2.addEdge(1, 2)<br\/>g2.addEdge(2, 3)<br\/>print &quot;Yes&quot; if g2.isSC() else &quot;No&quot;<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>Yes\r\nNo<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>PYTHON programming-Check if a graph is strongly connected | Set 1 (Kosaraju using DFS) &#8211; 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,4148],"tags":[78756,78755,78422,78754,78751,78750,78753,78752],"class_list":["post-26434","post","type-post","status-publish","format-standard","hentry","category-coding","category-connectivity","category-graph-algorithms","category-python","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\/26434","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=26434"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26434\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26434"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26434"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26434"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}