{"id":27123,"date":"2018-01-03T21:33:22","date_gmt":"2018-01-03T16:03:22","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27123"},"modified":"2018-01-03T21:33:22","modified_gmt":"2018-01-03T16:03:22","slug":"python-programming-bridges-graph","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-bridges-graph\/","title":{"rendered":"PYTHON programming Bridges in a graph"},"content":{"rendered":"<p>An edge in an undirected connected graph is a bridge iff removing it disconnects the graph. <span id=\"more-118009\"><\/span>For a disconnected undirected graph, definition is similar, a bridge is an edge removing which increases number of connected components.<br \/>\nLike <a href=\"http:\/\/www.geeksforgeeks.org\/articulation-points-or-cut-vertices-in-a-graph\/\" target=\"_blank\" rel=\"noopener noreferrer\">Articulation Points<\/a>,bridges represent vulnerabilities in a connected network and are useful for designing reliable networks. For example, in a wired computer network, an articulation point indicates the critical computers and a bridge indicates the critical wires or connections.<\/p>\n<p>Following are some example graphs with bridges highlighted with red color.<\/p>\n<p><strong>How to find all bridges in a given graph?<\/strong><br \/>\nA simple approach is to one by one remove all edges and see if removal of a edge causes disconnected graph. Following are steps of simple approach for connected graph.<\/p>\n<p>1) For every edge (u, v), do following<br \/>\n\u2026..a) Remove (u, v) from graph<br \/>\n..\u2026b) See if the graph remains connected (We can either use BFS or DFS)<br \/>\n\u2026..c) Add (u, v) back to the graph.<\/p>\n<p>Time complexity of above method is O(E*(V+E)) for a graph represented using adjacency list. Can we do better?<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>A O(V+E) algorithm to find all Bridges<\/strong><br \/>\nThe idea is similar to <a href=\"http:\/\/www.geeksforgeeks.org\/articulation-points-or-cut-vertices-in-a-graph\/\" target=\"_blank\" rel=\"noopener noreferrer\">O(V+E) algorithm for Articulation Points<\/a>. We do DFS traversal of the given graph. In DFS tree an edge (u, v) (u is parent of v in DFS tree) is bridge if there does not exit any other alternative to reach u or an ancestor of u from subtree rooted with v. As discussed in the <a href=\"http:\/\/www.geeksforgeeks.org\/articulation-points-or-cut-vertices-in-a-graph\/\" target=\"_blank\" rel=\"noopener noreferrer\">previous post<\/a>, the value low[v] indicates earliest visited vertex reachable from subtree rooted with v. <em>The condition for an edge (u, v) to be a bridge is, \u201clow[v] &gt; disc[u]\u201d<\/em>.<\/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 bridges in a given undirected graph<br\/>#Complexity : O(V+E)<br\/>  <br\/>from collections import defaultdict<br\/>  <br\/>#This class represents an undirected 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\/>        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\/>        self.graph[v].append(u)<br\/>  <br\/>    &#039;&#039;&#039;A recursive function that finds and prints bridges<br\/>    using DFS traversal<br\/>    u --&gt; The vertex to be visited next<br\/>    visited[] --&gt; keeps tract of visited vertices<br\/>    disc[] --&gt; Stores discovery times of visited vertices<br\/>    parent[] --&gt; Stores parent vertices in DFS tree&#039;&#039;&#039;<br\/>    def bridgeUtil(self,u, visited, parent, low, disc):<br\/> <br\/>        #Count of children in current node <br\/>        children =0<br\/> <br\/>        # Mark the current node as visited and print it<br\/>        visited[u]= True<br\/> <br\/>        # Initialize discovery time and low value<br\/>        disc[u] = self.Time<br\/>        low[u] = self.Time<br\/>        self.Time += 1<br\/> <br\/>        #Recur for all the vertices adjacent to this vertex<br\/>        for v in self.graph[u]:<br\/>            # If v is not visited yet, then make it a child of u<br\/>            # in DFS tree and recur for it<br\/>            if visited[v] == False :<br\/>                parent[v] = u<br\/>                children += 1<br\/>                self.bridgeUtil(v, visited, parent, low, disc)<br\/> <br\/>                # Check if the subtree rooted with v has a connection to<br\/>                # one of the ancestors of u<br\/>                low[u] = min(low[u], low[v])<br\/> <br\/> <br\/>                &#039;&#039;&#039; If the lowest vertex reachable from subtree<br\/>                under v is below u in DFS tree, then u-v is<br\/>                a bridge&#039;&#039;&#039;<br\/>                if low[v] &gt; disc[u]:<br\/>                    print (&quot;%d %d&quot; %(u,v))<br\/>     <br\/>                     <br\/>            elif v != parent[u]: # Update low value of u for parent function calls.<br\/>                low[u] = min(low[u], disc[v])<br\/> <br\/> <br\/>    # DFS based function to find all bridges. It uses recursive<br\/>    # function bridgeUtil()<br\/>    def bridge(self):<br\/>  <br\/>        # Mark all the vertices as not visited and Initialize parent and visited, <br\/>        # and ap(articulation point) arrays<br\/>        visited = [False] * (self.V)<br\/>        disc = [float(&quot;Inf&quot;)] * (self.V)<br\/>        low = [float(&quot;Inf&quot;)] * (self.V)<br\/>        parent = [-1] * (self.V)<br\/> <br\/>        # Call the recursive helper function to find bridges<br\/>        # in DFS tree rooted with vertex &#039;i&#039;<br\/>        for i in range(self.V):<br\/>            if visited[i] == False:<br\/>                self.bridgeUtil(i, visited, parent, low, disc)<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\/> <br\/>  <br\/>print &quot;Bridges in first graph &quot;<br\/>g1.bridge()<br\/> <br\/>g2 = Graph(4)<br\/>g2.addEdge(0, 1)<br\/>g2.addEdge(1, 2)<br\/>g2.addEdge(2, 3)<br\/>print &quot;\\nBridges in second graph &quot;<br\/>g2.bridge()<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;\\nBridges in third graph &quot;<br\/>g3.bridge()<br\/> <br\/> <\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>Bridges in first graph\r\n3 4\r\n0 3\r\n\r\nBridges in second graph\r\n2 3\r\n1 2\r\n0 1\r\n\r\nBridges in third graph\r\n1 6<\/pre>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>PYTHON programming &#8211; Bridges in a graph &#8211; An edge in an undirected connected graph is a bridge iff removing it disconnects the graph.<\/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":[79021,80897,80898,80899,80896,80900,80902,80901],"class_list":["post-27123","post","type-post","status-publish","format-standard","hentry","category-coding","category-connectivity","category-graph-algorithms","category-python","tag-articulation-points-and-bridges","tag-articulation-points-in-a-graph","tag-bridge-edge-seo","tag-bridge-graph-excel","tag-cut-vertex-graph-theory","tag-give-a-linear-time-algorithm-for-finding-the-bridges-in-a-graph","tag-graph-theory-bridge","tag-inverted-graph"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27123","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=27123"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27123\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27123"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27123"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27123"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}