{"id":26250,"date":"2017-10-26T21:12:27","date_gmt":"2017-10-26T15:42:27","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26250"},"modified":"2017-10-26T21:12:27","modified_gmt":"2017-10-26T15:42:27","slug":"python-programming-bellman-ford-algorithm-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/python-programming-bellman-ford-algorithm-2\/","title":{"rendered":"Python Programming-Bellman Ford Algorithm"},"content":{"rendered":"<p class=\"entry-title\">Given a graph and a source vertex src in graph, find shortest paths from src to all vertices in the given graph. The graph may contain negative weight edges.<\/p>\n<p class=\"entry-title\"><span id=\"more-27914\"><\/span>We have discussed <a href=\"http:\/\/www.geeksforgeeks.org\/archives\/27697\" target=\"_blank\" rel=\"noopener\">Dijkstra\u2019s algorithm<\/a> for this problem. Dijksra\u2019s algorithm is a Greedy algorithm and time complexity is O(VLogV) (with the use of Fibonacci heap). Dijkstra doesn\u2019t work for Graphs with negative weight edges, Bellman-Ford works for such graphs. Bellman-Ford is also simpler than Dijkstra and suites well for distributed systems. But time complexity of Bellman-Ford is O(VE), which is more than Dijkstra.<\/p>\n<h4 id=\"algorithm\"><strong>Algorithm<\/strong><\/h4>\n<h4 id=\"following-are-the-detailed-steps\">Following are the detailed steps.<\/h4>\n<p>Input: Graph and a source vertex src<br \/>\nOutput: Shortest distance to all vertices from src. If there is a negative weight cycle, then shortest distances are not calculated, negative weight cycle is reported.<\/p>\n<ol>\n<li>\u00a0This step initializes distances from source to all vertices as infinite and distance to source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.<\/li>\n<li>\u00a0This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given gra<br \/>\n<strong>a)<\/strong> Do following for each edge u-v<br \/>\nIf dist[v] &gt; dist[u] + weight of edge uv, then update dist[v]\ndist[v] = dist[u] + weight of edge uv<\/li>\n<li>\u00a0This step reports if there is a negative weight cycle in graph. Do following for each edge u-v<br \/>\nIf dist[v] &gt; dist[u] + weight of edge uv, then \u201cGraph contains negative weight cycle\u201d<br \/>\nThe idea of step 3 is, step 2 guarantees shortest distances if graph doesn\u2019t contain negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle<\/li>\n<\/ol>\n[ad type=&#8221;banner&#8221;]\n<p><strong>How does this work?<\/strong> Like other Dynamic Programming Problems, the algorithm calculate shortest paths in bottom-up manner. It first calculates the shortest distances for the shortest paths which have at-most one edge in the path. Then, it calculates shortest paths with at-nost 2 edges, and so on. After the ith iteration of outer loop, the shortest paths with at most i edges are calculated. There can be maximum |V| \u2013 1 edges in any simple path, that is why the outer loop runs |v| \u2013 1 times. The idea is, assuming that there is no negative weight cycle, if we have calculated shortest paths with at most i edges, then an iteration over all edges guarantees to give shortest path with at-most (i+1) edges (Proof is simple, you can refer <a href=\"http:\/\/courses.csail.mit.edu\/6.006\/spring11\/lectures\/lec15.pdf\" target=\"_blank\" rel=\"noopener\">this<\/a> or <a href=\"http:\/\/www.youtube.com\/watch?v=Ttezuzs39nk\" target=\"_blank\" rel=\"noopener\">MIT Video Lecture<\/a>)<\/p>\n<p><strong>Example<\/strong><br \/>\nLet us understand the algorithm with following example graph. The images are taken from <a href=\"http:\/\/www.cs.arizona.edu\/classes\/cs445\/spring07\/ShortestPath2.prn.pdf\" target=\"_blank\" rel=\"noopener\">this <\/a>source.<\/p>\n<p>Let the given source vertex be 0. Initialize all distances as infinite, except the distance to source itself. Total number of vertices in the graph is 5, so all edges must be processed 4 times.<\/p>\n<p><img fetchpriority=\"high\" decoding=\"async\" class=\"aligncenter size-full wp-image-26319\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Bellman\u2013Ford-Algorithm.png\" alt=\"Bellman\u2013Ford Algorithm\" width=\"439\" height=\"187\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Bellman\u2013Ford-Algorithm.png 439w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/Bellman\u2013Ford-Algorithm-300x128.png 300w\" sizes=\"(max-width: 439px) 100vw, 439px\" \/><\/p>\n<p>Let all edges are processed in following order: (B,E), (D,B), (B,D), (A,B), (A,C), (D,C), (B,C), (E,D). We get following distances when all edges are processed first time. The first row in shows initial distances. The second row shows distances when edges (B,E), (D,B), (B,D) and (A,B) are processed. The third row shows distances when (A,C) is processed. The fourth row shows when (D,C), (B,C) and (E,D) are processed.<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26329\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/C-Programming-Bellman\u2013Ford-Algorithm.png\" alt=\"C++ Programming-Bellman\u2013Ford Algorithm\" width=\"441\" height=\"202\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/C-Programming-Bellman\u2013Ford-Algorithm.png 441w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/C-Programming-Bellman\u2013Ford-Algorithm-300x137.png 300w\" sizes=\"(max-width: 441px) 100vw, 441px\" \/><\/p>\n<p>The first iteration guarantees to give all shortest paths which are at most 1 edge long. We get following distances when all edges are processed second time (The last row shows final values).<\/p>\n<p><img decoding=\"async\" class=\"aligncenter size-full wp-image-26334\" src=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/C-Programming-Bellman\u2013Ford-Algorithm-1.png\" alt=\"C++ Programming-Bellman\u2013Ford Algorithm\" width=\"430\" height=\"227\" srcset=\"https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/C-Programming-Bellman\u2013Ford-Algorithm-1.png 430w, https:\/\/www.wikitechy.com\/technology\/wp-content\/uploads\/2017\/05\/C-Programming-Bellman\u2013Ford-Algorithm-1-300x158.png 300w\" sizes=\"(max-width: 430px) 100vw, 430px\" \/><\/p>\n<p>The second iteration guarantees to give all shortest paths which are at most 2 edges long. The algorithm processes all edges 2 more times. The distances are minimized after the second iteration, so third and fourth iterations don\u2019t update the distances.<\/p>\n<p><strong>Phython Programming<\/strong><\/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 for Bellman-Ford&#039;s single source <br\/># shortest path algorithm.<br\/> <br\/>from collections import defaultdict<br\/> <br\/>#Class to represent a graph<br\/>class Graph:<br\/> <br\/>    def __init__(self,vertices):<br\/>        self.V= vertices #No. of vertices<br\/>        self.graph = [] # default dictionary to store graph<br\/>  <br\/>    # function to add an edge to graph<br\/>    def addEdge(self,u,v,w):<br\/>        self.graph.append([u, v, w])<br\/>         <br\/>    # utility function used to print the solution<br\/>    def printArr(self, dist):<br\/>        print(&quot;Vertex   Distance from Source&quot;)<br\/>        for i in range(self.V):<br\/>            print(&quot;%d \\t\\t %d&quot; % (i, dist[i]))<br\/>     <br\/>    # The main function that finds shortest distances from src to<br\/>    # all other vertices using Bellman-Ford algorithm.  The function<br\/>    # also detects negative weight cycle<br\/>    def BellmanFord(self, src):<br\/> <br\/>        # Step 1: Initialize distances from src to all other vertices<br\/>        # as INFINITE<br\/>        dist = [float(&quot;Inf&quot;)] * self.V<br\/>        dist[src] = 0<br\/> <br\/> <br\/>        # Step 2: Relax all edges |V| - 1 times. A simple shortest <br\/>        # path from src to any other vertex can have at-most |V| - 1 <br\/>        # edges<br\/>        for i in range(self.V - 1):<br\/>            # Update dist value and parent index of the adjacent vertices of<br\/>            # the picked vertex. Consider only those vertices which are still in<br\/>            # queue<br\/>            for u, v, w in self.graph:<br\/>                if dist[u] != float(&quot;Inf&quot;) and dist[u] + w &lt; dist[v]:<br\/>                        dist[v] = dist[u] + w<br\/> <br\/>        # Step 3: check for negative-weight cycles.  The above step <br\/>        # guarantees shortest distances if graph doesn&#039;t contain <br\/>        # negative weight cycle.  If we get a shorter path, then there<br\/>        # is a cycle.<br\/> <br\/>        for u, v, w in self.graph:<br\/>                if dist[u] != float(&quot;Inf&quot;) and dist[u] + w &lt; dist[v]:<br\/>                        print &quot;Graph contains negative weight cycle&quot;<br\/>                        return<br\/>                         <br\/>        # print all distance<br\/>        self.printArr(dist)<br\/> <br\/>g = Graph(5)<br\/>g.addEdge(0, 1, -1)<br\/>g.addEdge(0, 2, 4)<br\/>g.addEdge(1, 2, 3)<br\/>g.addEdge(1, 3, 2)<br\/>g.addEdge(1, 4, 2)<br\/>g.addEdge(3, 2, 5)<br\/>g.addEdge(3, 1, 1)<br\/>g.addEdge(4, 3, -3)<br\/> <br\/>#Print the solution<br\/>g.BellmanFord(0)<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<ul>\n<li>Vertex Distance from Source 0 0 1 -1 2 2 3 -2 4 1<\/li>\n<\/ul>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Notes<\/strong><br \/>\n<strong>1) <\/strong>Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.<\/p>\n<p><strong>2)<\/strong> Bellman-Ford works better (better than Dijksra\u2019s) for distributed systems. Unlike Dijksra\u2019s where we need to find minimum value of all vertices, in Bellman-Ford, edges are considered one by one.<\/p>\n<p><strong>Exercise<\/strong><br \/>\n<strong>1) <\/strong>The standard Bellman-Ford algorithm reports shortest path only if there is no negative weight cycles. Modify it so that it reports minimum distances even if there is a negative weight cycle.<\/p>\n<p><strong>2)<\/strong> Can we use Dijksra\u2019s algorithm for shortest paths for graphs with negative weights \u2013 one idea can be, calculate the minimum weight value, add a positive value (equal to absolute value of minimum weight value) to all weights and run the Dijksra\u2019s algorithm for the modified graph. Will this algorithm work?<\/p>\n[ad type=&#8221;banner&#8221;]\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python programming &#8211; bellman &#8211; ford &#8211; algorithm Given a graph and a source vertex src in graph, find shortest paths from src to all vertices<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,1,70145,73906,4148],"tags":[78466,74001,78383,78437,78465,78461,78449,78456,78379,78436,78444,78460,78458,78435,78442,78430,78445,78453,78463,78447,78455,78448,78434,78464,78452,78451,78454,78431,78440,78441,78439,78467,78384,78438,78450,78432,78380,78457,78462,74006,78433,78446,78443,78382,78459],"class_list":["post-26250","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-coding","category-dynamic-programming","category-graph-algorithms","category-python","tag-application-of-bellman-ford-algorithm","tag-bellman-ford-algorithm","tag-bellman-ford-algorithm-animation","tag-bellman-ford-algorithm-c","tag-bellman-ford-algorithm-c-code","tag-bellman-ford-algorithm-c-source-code","tag-bellman-ford-algorithm-code","tag-bellman-ford-algorithm-code-in-c","tag-bellman-ford-algorithm-example","tag-bellman-ford-algorithm-example-animation","tag-bellman-ford-algorithm-example-in-computer-networks","tag-bellman-ford-algorithm-example-pdf","tag-bellman-ford-algorithm-example-ppt","tag-bellman-ford-algorithm-example-step-by-step","tag-bellman-ford-algorithm-explained","tag-bellman-ford-algorithm-implementation-in-c","tag-bellman-ford-algorithm-in-c","tag-bellman-ford-algorithm-in-c-source-code","tag-bellman-ford-algorithm-in-c-with-output","tag-bellman-ford-algorithm-in-computer-networks","tag-bellman-ford-algorithm-in-java","tag-bellman-ford-algorithm-in-networking","tag-bellman-ford-algorithm-java","tag-bellman-ford-algorithm-java-code","tag-bellman-ford-algorithm-pdf","tag-bellman-ford-algorithm-ppt","tag-bellman-ford-algorithm-program-in-c-with-output","tag-bellman-ford-algorithm-pseudocode","tag-bellman-ford-algorithm-python","tag-bellman-ford-algorithm-simulation","tag-bellman-ford-algorithm-solved-example","tag-bellman-ford-algorithm-tutorial","tag-bellman-ford-algorithm-vs-dijkstra","tag-bellman-ford-algorithm-with-example","tag-bellman-ford-algorithmus","tag-bellman-ford-code-in-python","tag-bellman-ford-pseudocode","tag-c-program-for-bellman-ford-algorithm","tag-c-program-to-implement-bellman-ford-algorithm","tag-distance-vector-routing-algorithm","tag-distance-vector-routing-algorithm-python","tag-distributed-bellman-ford-algorithm","tag-example-of-bellman-ford-algorithm","tag-explain-bellman-ford-algorithm-with-example","tag-what-is-bellman-ford-algorithm"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26250","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=26250"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26250\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26250"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26250"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26250"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}