{"id":28372,"date":"2017-10-15T18:05:20","date_gmt":"2017-10-15T12:35:20","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=28372"},"modified":"2017-10-15T18:05:20","modified_gmt":"2017-10-15T12:35:20","slug":"tarjans-algorithm-find-strongly-connected-components","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/tarjans-algorithm-find-strongly-connected-components\/","title":{"rendered":"python programming Tarjan\u2019s Algorithm to find Strongly Connected Components"},"content":{"rendered":"<p>A directed graph is strongly connected if there is a path between all pairs of vertices.<span id=\"more-130872\"><\/span> A strongly connected component (<strong>SCC<\/strong>) of a directed graph is a maximal strongly connected subgraph. For example, there are 3 SCCs in the following graph.<\/p>\n<p>We have discussed Kosaraju\u2019s algorithm for strongly connected components. The previously discussed algorithm requires two DFS traversals of a Graph. In this post, Tarjan\u2019s algorithm is discussed that requires only one DFS traversal.<\/p>\n<p>Tarjan Algorithm is based on following facts:<br \/>\n1. DFS search produces a DFS tree\/forest<br \/>\n2. Strongly Connected Components form subtrees of the DFS tree.<br \/>\n3. If we can find head of such subtrees, we can print\/store all the nodes in that subtree (including head) and that will be one SCC.<br \/>\n4. There is no back edge from one SCC to another (There can be cross edges, but cross edges will not be used while processing the graph).<\/p>\n<p>To find head of a SCC, we calculate desc and low array (as done for articulation point, bridge, biconnected component). As discussed in the previous posts, low[u] indicates earliest visited vertex (the vertex with minimum discovery time) that can be reached from subtree rooted with u. A node u is head if disc[u] = low[u].[ad type=&#8221;banner&#8221;]\n<p><strong>Disc and Low Values<\/strong><br \/>\n(click on image to see it properly)<\/p>\n<p>Strongly Connected Component relates to directed graph only, but Disc and Low values relate to both directed and undirected graph, so in above pic we have taken an undirected graph.<\/p>\n<p>In above Figure, we have shown a graph and it\u2019s one of DFS tree (There could be different DFS trees on same graph depending on order in which edges are traversed).<br \/>\nIn DFS tree, continuous arrows are tree edges and dashed arrows are back edges (DFS Tree Edges<br \/>\nDisc and Low values are showin in Figure for every node as (Disc\/Low).<br \/>\n<strong>Disc:<\/strong> This is the time when a node is visited 1<sup>st<\/sup> time while DFS traversal. For nodes A, B, C, .., J in DFS tree, Disc values are 1, 2, 3, .., 10.<br \/>\n<strong>Low:<\/strong> In DFS tree, Tree edges take us forward, from ancestor node to one of it\u2019s descendants. For example, from node C, tree edges can take us to node node G, node I etc. Back edges take us backward, from a descendant node to one of it\u2019s ancestors. For example, from node G, Back edges take us to E or C. If we look at both Tree and Back edge together, then we can see that if we start traversal from one node, we may go down the tree via Tree edges and then go up via back edges. For example, from node E, we can go down to G and then go up to C. Similarly from E, we can go down to I or J and then go up to F. \u201cLow\u201d value of a node tells the topmost reachable ancestor (with minimum possible Disc value) via the subtree of that node. So for any node, Low value equal to it\u2019s Disc value anyway (A node is ancestor of itself). Then we look into it\u2019s subtree and see if there is any node which can take us to any of it\u2019s ancestor. If there are multiple back edges in subtree which take us to different ancestors, then we take the one with minimum Disc value (i.e. the topmost one). If we look at node F, it has two subtrees. Subtree with node G, takes us to E and C. The other subtree takes us back to F only. Here topmost ancestor is C where F can reach and so Low value of F is 3 (The Disc value of C).<br \/>\nBased on above discussion, it should be clear that Low values of B, C, and D are 1 (As A is the topmost node where B, C and D can reach). In same way, Low values of E, F, G are 3 and Low values of H, I, J are 6.[ad type=&#8221;banner&#8221;]\n<p>For any node u, when DFS starts, Low will be set to it\u2019s Disc 1<sup>st<\/sup>.<br \/>\nThen later on DFS will be performed on each of it\u2019s children v one by one, Low value of u can change it two case:<br \/>\n<strong>Case1 (Tree Edge):<\/strong> If node v is not visited already, then after DFS of v is complete, then minimum of low[u] and low[v] will be updated to low[u].<br \/>\nlow[u] = min(low[u], low[v]);<br \/>\n<strong>Case 2 (Back Edge):<\/strong> When child v is already visited, then minimum of low[u] and Disc[v] will be updated to low[u].<br \/>\nlow[u] = min(low[u], disc[v]);<br \/>\nIn case two, can we take low[v] instead of disc[v] ?? . Answer is <strong>NO<\/strong>. If you can think why answer is <strong>NO<\/strong>, you probably understood the Low and Disc concept.<br \/>\nImage Source: http:\/\/www.cs.yale.edu\/homes\/aspnes\/pinewiki\/DepthFirstSearch.html<br \/>\nSame Low and Disc values help to solve other graph problems like articulation point, bridge and biconnected component.<\/p>\n<p>To track the subtree rooted at head, we can use a stack (keep pushing node while visiting). When a head node found, pop all nodes from stack till you get head out of stack.<\/p>\n<p>To make sure, we don\u2019t consider cross edges, when we reach a node which is already visited, we should process the visited node only if it is present in stack, else ignore the node.<\/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 find strongly connected components in a given<br\/># directed graph using Tarjan&#039;s algorithm (single DFS)<br\/>#Complexity : O(V+E)<br\/>  <br\/>from collections import defaultdict<br\/>  <br\/>#This class represents an directed graph <br\/># using adjacency list representation<br\/>class Graph:<br\/>  <br\/>    def __init__(self,vertices):<br\/>        #No. of vertices<br\/>        self.V= vertices <br\/>         <br\/>        # default dictionary to store graph<br\/>        self.graph = defaultdict(list) <br\/>         <br\/>        self.Time = 0<br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v):<br\/>        self.graph[u].append(v)<br\/>         <br\/>  <br\/>    &#039;&#039;&#039;A recursive function that find finds and prints strongly connected<br\/>    components using DFS traversal<br\/>    u --&gt; The vertex to be visited next<br\/>    disc[] --&gt; Stores discovery times of visited vertices<br\/>    low[] -- &gt;&gt; earliest visited vertex (the vertex with minimum<br\/>                discovery time) that can be reached from subtree<br\/>                rooted with current vertex<br\/>    st -- &gt;&gt; To store all the connected ancestors (could be part<br\/>           of SCC)<br\/>    stackMember[] --&gt; bit\/index array for faster check whether<br\/>                  a node is in stack<br\/>    &#039;&#039;&#039;<br\/>    def SCCUtil(self,u, low, disc, stackMember, st):<br\/> <br\/>        # Initialize discovery time and low value<br\/>        disc[u] = self.Time<br\/>        low[u] = self.Time<br\/>        self.Time += 1<br\/>        stackMember[u] = True<br\/>        st.append(u)<br\/> <br\/>        # Go through all vertices adjacent to this<br\/>        for v in self.graph[u]:<br\/>             <br\/>            # If v is not visited yet, then recur for it<br\/>            if disc[v] == -1 :<br\/>             <br\/>                self.SCCUtil(v, low, disc, stackMember, st)<br\/> <br\/>                # Check if the subtree rooted with v has a connection to<br\/>                # one of the ancestors of u<br\/>                # Case 1 (per above discussion on Disc and Low value)<br\/>                low[u] = min(low[u], low[v])<br\/>                         <br\/>            elif stackMember[v] == True: <br\/> <br\/>                &#039;&#039;&#039;Update low value of &#039;u&#039; only if &#039;v&#039; is still in stack<br\/>                (i.e. it&#039;s a back edge, not cross edge).<br\/>                Case 2 (per above discussion on Disc and Low value) &#039;&#039;&#039;<br\/>                low[u] = min(low[u], disc[v])<br\/> <br\/>        # head node found, pop the stack and print an SCC<br\/>        w = -1 #To store stack extracted vertices<br\/>        if low[u] == disc[u]:<br\/>            while w != u:<br\/>                w = st.pop()<br\/>                print w,<br\/>                stackMember[w] = False<br\/>                 <br\/>            print&quot;&quot;<br\/>             <br\/>     <br\/> <br\/>    #The function to do DFS traversal. <br\/>    # It uses recursive SCCUtil()<br\/>    def SCC(self):<br\/>  <br\/>        # Mark all the vertices as not visited <br\/>        # and Initialize parent and visited, <br\/>        # and ap(articulation point) arrays<br\/>        disc = [-1] * (self.V)<br\/>        low = [-1] * (self.V)<br\/>        stackMember = [False] * (self.V)<br\/>        st =[]<br\/>         <br\/> <br\/>        # Call the recursive helper function <br\/>        # to find articulation points<br\/>        # in DFS tree rooted with vertex &#039;i&#039;<br\/>        for i in range(self.V):<br\/>            if disc[i] == -1:<br\/>                self.SCCUtil(i, low, disc, stackMember, st)<br\/> <br\/> <br\/>  <br\/>  <br\/>  <br\/># Create a graph given in the above diagram<br\/>g1 = Graph(5)<br\/>g1.addEdge(1, 0)<br\/>g1.addEdge(0, 2)<br\/>g1.addEdge(2, 1)<br\/>g1.addEdge(0, 3)<br\/>g1.addEdge(3, 4)<br\/>print &quot;SSC in first graph &quot;<br\/>g1.SCC()<br\/> <br\/>g2 = Graph(4)<br\/>g2.addEdge(0, 1)<br\/>g2.addEdge(1, 2)<br\/>g2.addEdge(2, 3)<br\/>print &quot;\\nSSC in second graph &quot;<br\/>g2.SCC()<br\/> <br\/>  <br\/>g3 = Graph(7)<br\/>g3.addEdge(0, 1)<br\/>g3.addEdge(1, 2)<br\/>g3.addEdge(2, 0)<br\/>g3.addEdge(1, 3)<br\/>g3.addEdge(1, 4)<br\/>g3.addEdge(1, 6)<br\/>g3.addEdge(3, 5)<br\/>g3.addEdge(4, 5)<br\/>print &quot;\\nSSC in third graph &quot;<br\/>g3.SCC()<br\/> <br\/>g4 = Graph(11)<br\/>g4.addEdge(0, 1)<br\/>g4.addEdge(0, 3)<br\/>g4.addEdge(1, 2)<br\/>g4.addEdge(1, 4)<br\/>g4.addEdge(2, 0)<br\/>g4.addEdge(2, 6)<br\/>g4.addEdge(3, 2)<br\/>g4.addEdge(4, 5)<br\/>g4.addEdge(4, 6)<br\/>g4.addEdge(5, 6)<br\/>g4.addEdge(5, 7)<br\/>g4.addEdge(5, 8)<br\/>g4.addEdge(5, 9)<br\/>g4.addEdge(6, 4)<br\/>g4.addEdge(7, 9)<br\/>g4.addEdge(8, 9)<br\/>g4.addEdge(9, 8)<br\/>print &quot;\\nSSC in fourth graph &quot;<br\/>g4.SCC();<br\/> <br\/> <br\/>g5 = Graph (5)<br\/>g5.addEdge(0, 1)<br\/>g5.addEdge(1, 2)<br\/>g5.addEdge(2, 3)<br\/>g5.addEdge(2, 4)<br\/>g5.addEdge(3, 0)<br\/>g5.addEdge(4, 2)<br\/>print &quot;\\nSSC in fifth graph &quot;<br\/>g5.SCC();<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>SCCs in first graph\r\n4\r\n3\r\n1 2 0\r\n\r\nSCCs in second graph\r\n3\r\n2\r\n1\r\n0\r\n\r\nSCCs in third graph\r\n5\r\n3\r\n4\r\n6\r\n2 1 0\r\n\r\nSCCs in fourth graph\r\n8 9\r\n7\r\n5 4 6\r\n3 2 1 0\r\n10\r\n\r\nSCCs in fifth graph\r\n4 3 2 1 0<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>python programming Tarjan\u2019s Algorithm to find Strongly Connected Components &#8211; Graph &#8211; A directed graph is strongly connected<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[78385,83522,73906,83524],"tags":[82041,82845,82091,82037,82090,82039,82040,82038],"class_list":["post-28372","post","type-post","status-publish","format-standard","hentry","category-connectivity","category-graph-2","category-graph-algorithms","category-graph-onnectivity","tag-counting-number-of-connected-components-in-a-undirected-graph","tag-strongly-connected-components-algorithm-example","tag-strongly-connected-components-c","tag-strongly-connected-components-code-in-c","tag-strongly-connected-components-example","tag-strongly-connected-components-kosaraju","tag-strongly-connected-components-undirected-graph","tag-tarjans-strongly-connected-components-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/28372","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=28372"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/28372\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=28372"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=28372"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=28372"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}