🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 42 (from laksa055)

2. Crawled Status Check

Query:
Response:

3. Robots.txt Check

Query:
Response:

4. Spam/Ban Check

Query:
Response:

5. Seen Status Check

ℹ️ Skipped - page is already crawled

đź“„
INDEXABLE
âś…
CRAWLED
11 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.4 months ago
History dropPASSisNull(history_drop_reason)No drop reason
Spam/banPASSfh_dont_index != 1 AND ml_spam_score = 0ml_spam_score=0
CanonicalPASSmeta_canonical IS NULL OR = '' OR = src_unparsedNot set

Page Details

PropertyValue
URLhttps://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/
Last Crawled2026-04-03 20:43:19 (11 days ago)
First Indexed2017-08-20 16:19:37 (8 years ago)
HTTP Status Code200
Meta TitlePython Programming-Bellman Ford Algorithm - Wikitechy
Meta DescriptionPython programming - bellman - ford - algorithm Given a graph and a source vertex src in graph, find shortest paths from src to all vertices
Meta Canonicalnull
Boilerpipe Text
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. We have discussed Dijkstra’s algorithm for this problem. Dijksra’s algorithm is a Greedy algorithm and time complexity is O(VLogV) (with the use of Fibonacci heap). Dijkstra doesn’t 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. Algorithm Following are the detailed steps. Input: Graph and a source vertex src Output: 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.  This 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.  This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given gra a) Do following for each edge u-v If dist[v] > dist[u] + weight of edge uv, then update dist[v] dist[v] = dist[u] + weight of edge uv  This step reports if there is a negative weight cycle in graph. Do following for each edge u-v If dist[v] > dist[u] + weight of edge uv, then “Graph contains negative weight cycle” The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t 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 [ad type=”banner”] How does this work? 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| – 1 edges in any simple path, that is why the outer loop runs |v| – 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 this or MIT Video Lecture ) Example Let us understand the algorithm with following example graph. The images are taken from this source. 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. 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. 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). 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’t update the distances. Phython Programming # Python program for Bellman-Ford's single source # shortest path algorithm. from collections import defaultdict #Class to represent a graph class Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = [] # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v,w): self.graph.append([u, v, w]) # utility function used to print the solution def printArr(self, dist): print("Vertex Distance from Source") for i in range(self.V): print("%d \t\t %d" % (i, dist[i])) # The main function that finds shortest distances from src to # all other vertices using Bellman-Ford algorithm. The function # also detects negative weight cycle def BellmanFord(self, src): # Step 1: Initialize distances from src to all other vertices # as INFINITE dist = [float("Inf")] * self.V dist[src] = 0 # Step 2: Relax all edges |V| - 1 times. A simple shortest # path from src to any other vertex can have at-most |V| - 1 # edges for i in range(self.V - 1): # Update dist value and parent index of the adjacent vertices of # the picked vertex. Consider only those vertices which are still in # queue for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: dist[v] = dist[u] + w # Step 3: check for negative-weight cycles. The above step # guarantees shortest distances if graph doesn't contain # negative weight cycle. If we get a shorter path, then there # is a cycle. for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: print "Graph contains negative weight cycle" return # print all distance self.printArr(dist) g = Graph(5) g.addEdge(0, 1, -1) g.addEdge(0, 2, 4) g.addEdge(1, 2, 3) g.addEdge(1, 3, 2) g.addEdge(1, 4, 2) g.addEdge(3, 2, 5) g.addEdge(3, 1, 1) g.addEdge(4, 3, -3) #Print the solution g.BellmanFord(0) Output: Vertex Distance from Source 0 0 1 -1 2 2 3 -2 4 1 [ad type=”banner”] Notes 1) 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. 2) Bellman-Ford works better (better than Dijksra’s) for distributed systems. Unlike Dijksra’s where we need to find minimum value of all vertices, in Bellman-Ford, edges are considered one by one. Exercise 1) 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. 2) Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – 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’s algorithm for the modified graph. Will this algorithm work? [ad type=”banner”]
Markdown
- [Resume](https://www.wikitechy.com/resume/) - [Letters](https://www.wikitechy.com/letters/) - [Interview Questions](https://www.wikitechy.com/interview-questions/) [![Wikitechy](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/wikitechy-dark.png) ![Wikitechy](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/wikitechy.png)](https://www.wikitechy.com/technology/ "Wikitechy") - [Home](https://www.wikitechy.com/) - [Tutorials](https://www.wikitechy.com/online-tutorials) - [Technology](https://www.wikitechy.com/technology/) - [Articles](https://www.wikitechy.com/articles/all/1) - [Errors & Fixes](https://www.wikitechy.com/errors-and-fixes/) - [Full Forms](https://www.wikitechy.com/full-form/) - [Projects](https://finalyearprojects.kaashivinfotech.com/) - [Videos](https://www.wikitechy.com/online-videos) - [Quantitative Aptitude](https://www.wikitechy.com/online-videos/aptitude-shortcuts-and-tricks/) - [Non Verbal](https://www.wikitechy.com/online-videos/non-verbal-reasoning-shortcuts-and-tricks/) - [Group Discussion](https://www.wikitechy.com/online-videos/group-discussion/what-is-group-discussion) - [Country Wise Interview Questions](https://www.wikitechy.com/interview-tips/country-wise-interview-questions) - [Engineering](https://www.wikitechy.com/engineering-interview-questions-and-answers) - [Careers](https://www.wikitechy.com/interview/index.html) - [HR Interview Q\&A](https://www.wikitechy.com/hr-interview-questions/) - [GD Interview](https://www.wikitechy.com/online-videos/group-discussion/what-is-group-discussion) - [Resume Samples](https://www.wikitechy.com/resume/) - [Letters](https://www.wikitechy.com/letters/) - [Engineering](https://www.wikitechy.com/engineering-interview-questions-and-answers/) - [Aptitude](https://www.wikitechy.com/online-videos/aptitude-shortcuts-and-tricks/) - [Reasoning](https://www.wikitechy.com/online-videos/non-verbal-reasoning-shortcuts-and-tricks/) - [Company Questions](https://www.wikitechy.com/online-videos/company-interview-questions-and-answers/) - [Country Wise Visa](https://www.wikitechy.com/visa/) - [Visa Dress Code](https://www.wikitechy.com/interview-outfits/) - [Business](https://www.wikitechy.com/hosting/) - [Top Web Hosting](https://www.wikitechy.com/hosting/) - [Top Car Accident Lawyers](https://www.wikitechy.com/car-accident/) - [Top Car Insurance](https://www.wikitechy.com/car-insurance/) - [Top Software Tools](https://www.wikitechy.com/) - [Top 10](https://www.wikitechy.com/top10/) - [Lung Cancer](https://www.wikitechy.com/mesothelioma) [Write for Us](https://www.wikitechy.com/write-for-us/) Close ### Type and hit Enter to search Popular Searches: [Nature](https://www.wikitechy.com/technology/?s=Nature "Nature") [Musical](https://www.wikitechy.com/technology/?s=Musical "Musical") [Guide](https://www.wikitechy.com/technology/?s=Guide "Guide") [![Wikitechy](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/wikitechy-dark.png) ![Wikitechy](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/wikitechy.png)](https://www.wikitechy.com/technology/ "Wikitechy") Close ### Type and hit Enter to search Popular Searches: [Nature](https://www.wikitechy.com/technology/?s=Nature "Nature") [Musical](https://www.wikitechy.com/technology/?s=Musical "Musical") [Guide](https://www.wikitechy.com/technology/?s=Guide "Guide") [Home](https://www.wikitechy.com/technology/)*/*[Algorithm](https://www.wikitechy.com/technology/category/algorithm/)*/*Python Programming-Bellman Ford Algorithm [Algorithm](https://www.wikitechy.com/technology/category/algorithm/ "Algorithm")[Coding](https://www.wikitechy.com/technology/category/coding/ "Coding")[Dynamic Programming](https://www.wikitechy.com/technology/category/algorithm/dynamic-programming/ "Dynamic Programming")[Graph Algorithms](https://www.wikitechy.com/technology/category/algorithm/graph-algorithms/ "Graph Algorithms")[PYTHON](https://www.wikitechy.com/technology/category/coding/python/ "PYTHON") # Python Programming-Bellman Ford Algorithm [![](https://secure.gravatar.com/avatar/155b77fd8cdda3d0913fcb7e7ee63543b0c345d2d8f6dcebda5b0583ab61f967?s=45&r=g)](https://www.wikitechy.com/technology/author/webmaster/) By [Venkatesan Prabu](https://www.wikitechy.com/technology/author/webmaster/) October 26, 2017 4 Min Read 421 0 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. We have discussed [Dijkstra’s algorithm](http://www.geeksforgeeks.org/archives/27697) for this problem. Dijksra’s algorithm is a Greedy algorithm and time complexity is O(VLogV) (with the use of Fibonacci heap). Dijkstra doesn’t 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. #### **Algorithm** #### Following are the detailed steps. Input: Graph and a source vertex src Output: 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. 1. This 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. 2. This step calculates shortest distances. Do following \|V\|-1 times where \|V\| is the number of vertices in given gra **a)** Do following for each edge u-v If dist\[v\] \> dist\[u\] + weight of edge uv, then update dist\[v\] dist\[v\] = dist\[u\] + weight of edge uv 3. This step reports if there is a negative weight cycle in graph. Do following for each edge u-v If dist\[v\] \> dist\[u\] + weight of edge uv, then “Graph contains negative weight cycle” The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t 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 \[ad type=”banner”\] **How does this work?** 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\| – 1 edges in any simple path, that is why the outer loop runs \|v\| – 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 [this](http://courses.csail.mit.edu/6.006/spring11/lectures/lec15.pdf) or [MIT Video Lecture](https://www.youtube.com/watch?v=Ttezuzs39nk)) **Example** Let us understand the algorithm with following example graph. The images are taken from [this](http://www.cs.arizona.edu/classes/cs445/spring07/ShortestPath2.prn.pdf) source. 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. ![Bellman–Ford Algorithm](https://www.wikitechy.com/technology/wp-content/uploads/2017/05/Bellman%E2%80%93Ford-Algorithm.png) 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. ![C++ Programming-Bellman–Ford Algorithm](https://www.wikitechy.com/technology/wp-content/uploads/2017/05/C-Programming-Bellman%E2%80%93Ford-Algorithm.png) 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). ![C++ Programming-Bellman–Ford Algorithm](https://www.wikitechy.com/technology/wp-content/uploads/2017/05/C-Programming-Bellman%E2%80%93Ford-Algorithm-1.png) 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’t update the distances. **Phython Programming** ``` # Python program for Bellman-Ford's single source # shortest path algorithm. from collections import defaultdict #Class to represent a graph class Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = [] # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v,w): self.graph.append([u, v, w]) # utility function used to print the solution def printArr(self, dist): print("Vertex Distance from Source") for i in range(self.V): print("%d \t\t %d" % (i, dist[i])) # The main function that finds shortest distances from src to # all other vertices using Bellman-Ford algorithm. The function # also detects negative weight cycle def BellmanFord(self, src): # Step 1: Initialize distances from src to all other vertices # as INFINITE dist = [float("Inf")] * self.V dist[src] = 0 # Step 2: Relax all edges |V| - 1 times. A simple shortest # path from src to any other vertex can have at-most |V| - 1 # edges for i in range(self.V - 1): # Update dist value and parent index of the adjacent vertices of # the picked vertex. Consider only those vertices which are still in # queue for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: dist[v] = dist[u] + w # Step 3: check for negative-weight cycles. The above step # guarantees shortest distances if graph doesn't contain # negative weight cycle. If we get a shorter path, then there # is a cycle. for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: print "Graph contains negative weight cycle" return # print all distance self.printArr(dist) g = Graph(5) g.addEdge(0, 1, -1) g.addEdge(0, 2, 4) g.addEdge(1, 2, 3) g.addEdge(1, 3, 2) g.addEdge(1, 4, 2) g.addEdge(3, 2, 5) g.addEdge(3, 1, 1) g.addEdge(4, 3, -3) #Print the solution g.BellmanFord(0) ``` Output: - Vertex Distance from Source 0 0 1 -1 2 2 3 -2 4 1 \[ad type=”banner”\] **Notes** **1\)** 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. **2\)** Bellman-Ford works better (better than Dijksra’s) for distributed systems. Unlike Dijksra’s where we need to find minimum value of all vertices, in Bellman-Ford, edges are considered one by one. **Exercise** **1\)** 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. **2\)** Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – 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’s algorithm for the modified graph. Will this algorithm work? \[ad type=”banner”\] Total 0 Shares [Share 0](https://www.facebook.com/sharer.php?u=https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/) [Tweet 0](https://twitter.com/share?&text=Python%20Programming-Bellman%20Ford%20Algorithm&url=https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/) [Pin it 0](https://pinterest.com/pin/create/bookmarklet/?url=https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/) [Share 0](https://www.wikitechy.com/cdn-cgi/l/email-protection#66591513040c0305125b361f120e09084354563614090114070b0b0f08014b24030a0a0b070843545620091402435456270a0109140f120e0b400409021f5b361f120e09084354563614090114070b0b0f08014b24030a0a0b070843545620091402435456270a0109140f120e0b4354560e121216155c494911111148110f0d0f1203050e1f4805090b491203050e08090a09011f49161f120e09084b1614090114070b0b0f08014b04030a0a0b07084b000914024b070a0109140f120e0b4b5449) #### Tags: [application of bellman ford algorithm](https://www.wikitechy.com/technology/tag/application-of-bellman-ford-algorithm/)[bellman ford algorithm](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm/)[bellman ford algorithm animation](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-animation/)[bellman ford algorithm c](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-c/)[bellman ford algorithm c code](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-c-code/)[bellman ford algorithm c++ source code](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-c-source-code/)[bellman ford algorithm code](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-code/)[bellman ford algorithm code in c](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-code-in-c/)[bellman ford algorithm example](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-example/)[bellman ford algorithm example animation](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-example-animation/)[bellman ford algorithm example in computer networks](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-example-in-computer-networks/)[bellman ford algorithm example pdf](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-example-pdf/)[bellman ford algorithm example ppt](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-example-ppt/)[bellman ford algorithm example step by step](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-example-step-by-step/)[bellman ford algorithm explained](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-explained/)[bellman ford algorithm implementation in c](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-implementation-in-c/)[bellman ford algorithm in c](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-in-c/)[bellman ford algorithm in c source code](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-in-c-source-code/)[bellman ford algorithm in c with output](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-in-c-with-output/)[bellman ford algorithm in computer networks](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-in-computer-networks/)[bellman ford algorithm in java](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-in-java/)[bellman ford algorithm in networking](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-in-networking/)[bellman ford algorithm java](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-java/)[bellman ford algorithm java code](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-java-code/)[bellman ford algorithm pdf](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-pdf/)[bellman ford algorithm ppt](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-ppt/)[bellman ford algorithm program in c with output](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-program-in-c-with-output/)[bellman ford algorithm pseudocode](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-pseudocode/)[bellman ford algorithm python](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-python/)[bellman ford algorithm simulation](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-simulation/)[bellman ford algorithm solved example](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-solved-example/)[bellman ford algorithm tutorial](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-tutorial/)[bellman ford algorithm vs dijkstra](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-vs-dijkstra/)[bellman ford algorithm with example](https://www.wikitechy.com/technology/tag/bellman-ford-algorithm-with-example/)[bellman ford algorithmus](https://www.wikitechy.com/technology/tag/bellman-ford-algorithmus/)[bellman ford code in python](https://www.wikitechy.com/technology/tag/bellman-ford-code-in-python/)[bellman ford pseudocode](https://www.wikitechy.com/technology/tag/bellman-ford-pseudocode/)[c program for bellman ford algorithm](https://www.wikitechy.com/technology/tag/c-program-for-bellman-ford-algorithm/)[c program to implement bellman ford algorithm](https://www.wikitechy.com/technology/tag/c-program-to-implement-bellman-ford-algorithm/)[distance vector routing algorithm](https://www.wikitechy.com/technology/tag/distance-vector-routing-algorithm/)[distance vector routing algorithm python](https://www.wikitechy.com/technology/tag/distance-vector-routing-algorithm-python/)[distributed bellman ford algorithm](https://www.wikitechy.com/technology/tag/distributed-bellman-ford-algorithm/)[example of bellman ford algorithm](https://www.wikitechy.com/technology/tag/example-of-bellman-ford-algorithm/)[explain bellman-ford algorithm with example](https://www.wikitechy.com/technology/tag/explain-bellman-ford-algorithm-with-example/)[what is bellman ford algorithm](https://www.wikitechy.com/technology/tag/what-is-bellman-ford-algorithm/) #### Share Article Link Copied\! [![](https://secure.gravatar.com/avatar/155b77fd8cdda3d0913fcb7e7ee63543b0c345d2d8f6dcebda5b0583ab61f967?s=120&r=g)](https://www.wikitechy.com/technology/author/webmaster/) Author #### [Venkatesan Prabu](https://www.wikitechy.com/technology/author/webmaster/) Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events. [Follow Me](https://www.wikitechy.com/technology/author/webmaster/) ##### Other Articles Previous ### [Greedy Algorithms \| Set 2 (Kruskal’s Minimum Spanning Tree Algorithm)](https://www.wikitechy.com/technology/greedy-algorithms-set-2-kruskals-minimum-spanning-tree-algorithm-2/) Next ### [Palindrome Partitioning](https://www.wikitechy.com/technology/palindrome-partitioning/) ##### No Comment! Be the first one. ### Leave a Reply [![instagram profile](https://www.wikitechy.com/technology/wp-content/uploads/2024/09/kaashiv-150x150.png)](https://www.youtube.com/@kaashiv) [@kaashiv](https://www.youtube.com/@kaashiv) [Follow Me](https://www.youtube.com/@kaashiv) #### Popular Posts ###### [Download Huawei P9 Lite Android Nougat Update \[B336\]](https://www.wikitechy.com/technology/download-huawei-p9-lite-android-nougat-update-b336/ "Download Huawei P9 Lite Android Nougat Update [B336]") [ANDROID](https://www.wikitechy.com/technology/category/android/) ###### [How to Install TWRP Recovery and Root Mi5s & Mi5s Plus](https://www.wikitechy.com/technology/root-mi5s-and-mi5s-plus/ "How to Install TWRP Recovery and Root Mi5s & Mi5s Plus") [ANDROID](https://www.wikitechy.com/technology/category/android/) ###### [How to Downgrade Honor 5c from Nougat to Marshmallow](https://www.wikitechy.com/technology/downgrade-honor-5c-nougat-marshmallow/ "How to Downgrade Honor 5c from Nougat to Marshmallow") [ANDROID](https://www.wikitechy.com/technology/category/android/) ###### [Download ZTE Axon 7 Android 7.1 Nougat Update (MiFavor 4.2)(B13)](https://www.wikitechy.com/technology/download-zte-axon-7-android-7-1-nougat-update-mifavor-4-2b13/ "Download ZTE Axon 7 Android 7.1 Nougat Update (MiFavor 4.2)(B13)") [ANDROID](https://www.wikitechy.com/technology/category/android/) #### Categories [1xbet](https://www.wikitechy.com/technology/category/1xbet/) [3D animation company](https://www.wikitechy.com/technology/category/companies/3d-animation-company/) [Activity](https://www.wikitechy.com/technology/category/activity/) [add page numbers to pdf](https://www.wikitechy.com/technology/category/pdf/add-page-numbers-to-pdf/) [Advertising Platforms](https://www.wikitechy.com/technology/category/advertising-platforms/) [air conditioner](https://www.wikitechy.com/technology/category/electronics/air-conditioner/) [Algorithm](https://www.wikitechy.com/technology/category/algorithm/) [Analysis of Algorithm](https://www.wikitechy.com/technology/category/algorithm/analysis-of-algorithm/) [Andriod](https://www.wikitechy.com/technology/category/andriod/) [ANDROID](https://www.wikitechy.com/technology/category/android/) ### Related Posts ![3 Ideas to Optimize Emission Control Algorithms for a Warming World](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/3-Ideas-to-Optimize-Emission-Control-Algorithms-for-a-Warming-World-150x150.jpg) ![3 Ideas to Optimize Emission Control Algorithms for a Warming World](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/3-Ideas-to-Optimize-Emission-Control-Algorithms-for-a-Warming-World-150x150.jpg) ##### [3 Ideas to Optimize Emission Control Algorithms for a Warming World](https://www.wikitechy.com/technology/3-ideas-to-optimize-emission-control-algorithms-for-a-warming-world/ "3 Ideas to Optimize Emission Control Algorithms for a Warming World") By [Venkatesan Prabu](https://www.wikitechy.com/technology/author/webmaster/) [Algorithm](https://www.wikitechy.com/technology/category/algorithm/) ![AI](https://www.wikitechy.com/technology/wp-content/uploads/2025/09/WhatsApp-Image-2025-09-17-at-18.43.31_27da6ff7-150x150.jpg) ![AI](https://www.wikitechy.com/technology/wp-content/uploads/2025/09/WhatsApp-Image-2025-09-17-at-18.43.31_27da6ff7-150x150.jpg) ##### [AI Image Generators: Redefining the Way We Create Visual Storytelling](https://www.wikitechy.com/technology/ai-image-generators-redefining-the-way-we-create-visual-storytelling/ "AI Image Generators: Redefining the Way We Create Visual Storytelling") By [Venkatesan Prabu](https://www.wikitechy.com/technology/author/webmaster/) [artificial intelligence](https://www.wikitechy.com/technology/category/algorithm/artificial-intelligence/) ![AI](https://www.wikitechy.com/technology/wp-content/uploads/2025/08/The-Future-of-Product-Development-AIs-Role-Beyond-Management-150x150.png) ![AI](https://www.wikitechy.com/technology/wp-content/uploads/2025/08/The-Future-of-Product-Development-AIs-Role-Beyond-Management-150x150.png) ##### [The Future of Product Development: AI’s Role Beyond Management](https://www.wikitechy.com/technology/the-future-of-product-development-ais-role-beyond-management/ "The Future of Product Development: AI’s Role Beyond Management") By [Venkatesan Prabu](https://www.wikitechy.com/technology/author/webmaster/) [artificial intelligence](https://www.wikitechy.com/technology/category/algorithm/artificial-intelligence/) ![](https://www.wikitechy.com/technology/wp-content/uploads/2025/10/wikitechy-dark.png) [Privacy Policy](https://www.wikitechy.com/privacy-policy-2/) [Contact Us](https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/wikitechy.com@gmail.com) [Write for Us](https://www.wikitechy.com/write-for-us/) #### Top Trending Courses [Full Stack .Net Course](https://www.kaashivinfotech.com/dotnet-full-stack-development-course-in-chennai/) [Full Stack Java Course](https://www.kaashivinfotech.com/java-full-stack-developer/) [Full Stack Python Course](https://www.kaashivinfotech.com/python-full-stack-development-course-in-chennai/) [Data Science Course](https://www.kaashivinfotech.com/data-science-course/) [Artificial Intelligence Course](https://www.kaashivinfotech.com/artificial-intelligence-course/) [Data Analytics Course](https://www.kaashivinfotech.com/data-analytics-course-in-chennai/) [Networking Course](https://www.kaashivinfotech.com/networking-training-in-chennai/) [Cyber Security Course](https://www.kaashivinfotech.com/cyber-security-course-in-chennai/) [Cloud Computing Course](https://www.kaashivinfotech.com/cloud-computing-course-in-chennai/) [Devops Course](https://www.kaashivinfotech.com/devops-course-in-chennai/) #### Technology Internships [SQL Internship](https://internship.kaashivinfotech.com/sql-internship/) [Python Internship](https://internship.kaashivinfotech.com/python-internship/) [Java Internship](https://internship.kaashivinfotech.com/java-internship/) [IoT Internship](https://internship.kaashivinfotech.com/iot-internship/) [Data Science Internship](https://internship.kaashivinfotech.com/data-science-internship/) [Cyber Security Internship](https://internship.kaashivinfotech.com/cyber-security-internship/) [Cloud Computing Internship](https://internship.kaashivinfotech.com/cloud-computing-internship/) [Artificial Intelligence Internship](https://internship.kaashivinfotech.com/artificial-intelligence-internship/) [Embedded System Internship](https://internship.kaashivinfotech.com/embedded-system-internship/) #### Top Trending Tutorials [Ethical Hacking Tutorial](https://www.wikitechy.com/tutorials/ethical-hacking/) \| [C\# Tutorial](https://www.wikitechy.com/tutorials/csharp/) \| [Linear Integrated Circuits Tutorial](https://www.wikitechy.com/tutorials/linear-integrated-circuits/) \| [Python Tutorial](https://www.wikitechy.com/tutorials/python/) \| [SQL Tutorial](https://www.wikitechy.com/tutorials/sql/) \| [Compiler Design Tutorial](https://www.wikitechy.com/tutorials/compiler-design/) \| [Java Tutorial](https://www.wikitechy.com/tutorials/java/) \| [HTML Tutorial](https://www.wikitechy.com/step-by-step-html-tutorials/) \| [Javascript Tutorial](https://www.wikitechy.com/tutorials/javascript/) \| [ReactJS Tutorial](https://www.wikitechy.com/tutorials/react/react-js-tutorial) #### Technology Interview Questions [Latex Interview Questions](https://www.wikitechy.com/interview-questions/category/latex/) \| [SQL Interview Questions](https://www.wikitechy.com/interview-questions/category/sql/) \| [Networking Interview Questions](https://www.wikitechy.com/interview-questions/category/networking/) \| [Java Interview Questions](https://www.wikitechy.com/interview-questions/category/java/) \| [ReactJS Interview Questions](https://www.wikitechy.com/interview-questions/category/reactjs/) \| [Cyber Security Interview Questions](https://www.wikitechy.com/interview-questions/category/cyber-security/) \| [Python Interview Questions](https://www.wikitechy.com/interview-questions/category/python/) \| [C\# Interview Questions](https://www.wikitechy.com/interview-questions/category/csharp/) \| [Big Data Interview Questions](https://www.wikitechy.com/interview-questions/category/big-data/) \| [Sqoop Interview Questions](https://www.wikitechy.com/interview-questions/category/sqoop/) #### General Interview Questions [Electrical Engineering](https://www.wikitechy.com/interview-questions/category/electrical-engineering/) \| [Clock](https://www.wikitechy.com/interview-questions/category/clock/) \| [Numbers](https://www.wikitechy.com/interview-questions/category/numbers/) \| [Number Series](https://www.wikitechy.com/interview-questions/category/number-series/) \| [Percentage](https://www.wikitechy.com/interview-questions/category/percentage/) \| [Tenses and Articles](https://www.wikitechy.com/interview-questions/category/tenses-and-articles/) \| [Puzzles](https://www.wikitechy.com/interview-questions/category/puzzles/) \| [Calendar](https://www.wikitechy.com/interview-questions/category/calendar/) \| [Profit and Loss](https://www.wikitechy.com/interview-questions/category/profit-and-loss/) \| [Programming](https://www.wikitechy.com/interview-questions/category/programming/) \| [LaTeX](https://www.wikitechy.com/interview-questions/category/latex/) \| [Speech and Voices](https://www.wikitechy.com/interview-questions/category/speech-and-voices/) \| [LCM and HCF](https://www.wikitechy.com/interview-questions/category/lcm-and-hcf/) #### HR Interview Questions [Why You’re Fit for the Role](https://www.wikitechy.com/hr-interview-questions/why-do-you-consider-yourself-a-suitable-candidate-for-this-position) \| [How You Spent Last Sunday](https://www.wikitechy.com/hr-interview-questions/how-did-you-spend-your-last-day-sunday) \| [Tell me about Bangalore traffic](https://www.wikitechy.com/hr-interview-questions/tell-me-about-bangalore-traffic) \| [60-Day Strategy if Selected](https://www.wikitechy.com/hr-interview-questions/assuming-that-you-are-selected-what-will-be-your-strategy-for-next-60-days) \| [Long Stay in Current Job](https://www.wikitechy.com/hr-interview-questions/why-you-have-stayed-in-your-current-job-for-long-time) \| [Daily Routine](https://www.wikitechy.com/hr-interview-questions/what-is-your-daily-routine) \| [Talk on Latest Movie](https://www.wikitechy.com/hr-interview-questions/speak-for-two-minutes-on-a-latest-movie) \| [Decision Challenged by Colleague/Manager](https://www.wikitechy.com/hr-interview-questions/have-there-been-instances-when-your-decision-was-challenged-by-your-colleague-or-manager) \| [Salary Expectations](https://www.wikitechy.com/hr-interview-questions/what-are-your-salary-expectations) \| [Compensating Lack of Experience](https://www.wikitechy.com/hr-interview-questions/how-to-compensate-for-lack-of-experience) #### Full Forms [JOB Full Form](https://www.wikitechy.com/full-form/job-full-form) \| [TC Full Form](https://www.wikitechy.com/full-form/tc-full-form) \| [BYE Full Form](https://www.wikitechy.com/full-form/bye-full-form) \| [VIDEO Full Form](https://www.wikitechy.com/full-form/video-full-form) \| [HTML](https://www.wikitechy.com/html-full-form/) \| [XEN](https://www.wikitechy.com/full-form/xen-full-form) \| [LBS Full Form](https://www.wikitechy.com/full-form/lbs-full-form) \| [TVS Full Form](https://www.wikitechy.com/full-form/tvs-full-form) \| [COM Full Form](https://www.wikitechy.com/full-form/com-full-form) \| [LT Full Form](https://www.wikitechy.com/full-form/lt-full-form) \| [SGL Full Form](https://www.wikitechy.com/full-form/sgl-full-form) \| [MMS Full Form](https://www.wikitechy.com/full-form/mms-full-form) \| [PFA Full Form](https://www.wikitechy.com/full-form/pfa-full-form) \| [ASAP Full Form](https://www.wikitechy.com/full-form/asap-full-form) \| [WWE Full Form](https://www.wikitechy.com/full-form/wwe-full-form) \| [JIO Full Form](https://www.wikitechy.com/full-form/jio-full-form) \| [KB Full Form](https://www.wikitechy.com/full-form/kb-full-form) \| [DJ Full Form](https://www.wikitechy.com/full-form/dj-full-form) #### Resume [SSLC Resume](https://www.wikitechy.com/resume/sslc-resume-format-and-samples-sslc-qualification-resume-format-hr-letter-formats/) \| [ICICI Bank Deputy Manager Resume](https://www.wikitechy.com/resume/icici-bank-deputy-manager-resume/) \| [Assistant Finance Manager Resume](https://www.wikitechy.com/resume/assistant-finance-manager-resume-samples/) \| [Software Developer Resume](https://www.wikitechy.com/resume/software-developer-resume-examples/) \| [Accounting Clerk Resume](https://www.wikitechy.com/resume/sample-accounting-clerk-resume/) \| [BCA Fresher Resume](https://www.wikitechy.com/resume/bca-fresher-resume-sample/) \| [Retired Person Resume](https://www.wikitechy.com/resume/resume-for-retired-person-sample/) \| [HR Executive Resume](https://www.wikitechy.com/resume/hr-executive-resume-samples/) \| [Computer Engineer Fresher Resume](https://www.wikitechy.com/resume/fresher-computer-engineers-resume-sample/) #### Letters [Security Guard Recommendation Letter](https://www.wikitechy.com/letters/sample-recommendation-letter-security-guard/) \| [Chef Recommendation Letter](https://www.wikitechy.com/letters/chef-recommendation-letter-sample/) \| [Gifted & Talented Recommendation Letter](https://www.wikitechy.com/letters/sample-recommendation-letter-gifted-talented/) \| [Attendance Confirmation Letter](https://www.wikitechy.com/letters/confirming-attendance-lette/) \| [CNA Reference Letter](https://www.wikitechy.com/letters/sample-cna-reference-letter/) \| [Real Estate Agent Recommendation Letter](https://www.wikitechy.com/letters/sample-recommendation-letter-real-estate-agent/) \| [Software Engineer Recommendation Letter](https://www.wikitechy.com/letters/software-engineer-recommendation-letter-sample/) \| [Dental Assistant Recommendation Letter](https://www.wikitechy.com/letters/sample-recommendation-letter-dental-assistant/) \| [Hotel Sales Letter](https://www.wikitechy.com/letters/hotel-sales-letter/) \| [Complaint About Authority Misconduct Letter](https://www.wikitechy.com/letters/complain-manhandling-authorities/) © 2016 Wikitechy. All rights reserved. [Scroll](https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/) Our site uses cookies. By using this site, you agree to the [Privacy Policy](https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/) and [Terms of Use](https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/). [Accept](https://www.wikitechy.com/technology/python-programming-bellman-ford-algorithm-2/) - [Home](https://www.wikitechy.com/) - [Tutorials](https://www.wikitechy.com/online-tutorials) - [Technology](https://www.wikitechy.com/technology/) - [Articles](https://www.wikitechy.com/articles/all/1) - [Errors & Fixes](https://www.wikitechy.com/errors-and-fixes/) - [Full Forms](https://www.wikitechy.com/full-form/) - [Projects](https://finalyearprojects.kaashivinfotech.com/) - [Videos](https://www.wikitechy.com/online-videos) - [Quantitative Aptitude](https://www.wikitechy.com/online-videos/aptitude-shortcuts-and-tricks/) - [Non Verbal](https://www.wikitechy.com/online-videos/non-verbal-reasoning-shortcuts-and-tricks/) - [Group Discussion](https://www.wikitechy.com/online-videos/group-discussion/what-is-group-discussion) - [Country Wise Interview Questions](https://www.wikitechy.com/interview-tips/country-wise-interview-questions) - [Engineering](https://www.wikitechy.com/engineering-interview-questions-and-answers) - [Careers](https://www.wikitechy.com/interview/index.html) - [HR Interview Q\&A](https://www.wikitechy.com/hr-interview-questions/) - [GD Interview](https://www.wikitechy.com/online-videos/group-discussion/what-is-group-discussion) - [Resume Samples](https://www.wikitechy.com/resume/) - [Letters](https://www.wikitechy.com/letters/) - [Engineering](https://www.wikitechy.com/engineering-interview-questions-and-answers/) - [Aptitude](https://www.wikitechy.com/online-videos/aptitude-shortcuts-and-tricks/) - [Reasoning](https://www.wikitechy.com/online-videos/non-verbal-reasoning-shortcuts-and-tricks/) - [Company Questions](https://www.wikitechy.com/online-videos/company-interview-questions-and-answers/) - [Country Wise Visa](https://www.wikitechy.com/visa/) - [Visa Dress Code](https://www.wikitechy.com/interview-outfits/) - [Business](https://www.wikitechy.com/hosting/) - [Top Web Hosting](https://www.wikitechy.com/hosting/) - [Top Car Accident Lawyers](https://www.wikitechy.com/car-accident/) - [Top Car Insurance](https://www.wikitechy.com/car-insurance/) - [Top Software Tools](https://www.wikitechy.com/) - [Top 10](https://www.wikitechy.com/top10/) - [Lung Cancer](https://www.wikitechy.com/mesothelioma)
Readable Markdown
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. We have discussed [Dijkstra’s algorithm](http://www.geeksforgeeks.org/archives/27697) for this problem. Dijksra’s algorithm is a Greedy algorithm and time complexity is O(VLogV) (with the use of Fibonacci heap). Dijkstra doesn’t 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. #### **Algorithm** #### Following are the detailed steps. Input: Graph and a source vertex src Output: 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. 1. This 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. 2. This step calculates shortest distances. Do following \|V\|-1 times where \|V\| is the number of vertices in given gra **a)** Do following for each edge u-v If dist\[v\] \> dist\[u\] + weight of edge uv, then update dist\[v\] dist\[v\] = dist\[u\] + weight of edge uv 3. This step reports if there is a negative weight cycle in graph. Do following for each edge u-v If dist\[v\] \> dist\[u\] + weight of edge uv, then “Graph contains negative weight cycle” The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t 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 \[ad type=”banner”\] **How does this work?** 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\| – 1 edges in any simple path, that is why the outer loop runs \|v\| – 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 [this](http://courses.csail.mit.edu/6.006/spring11/lectures/lec15.pdf) or [MIT Video Lecture](https://www.youtube.com/watch?v=Ttezuzs39nk)) **Example** Let us understand the algorithm with following example graph. The images are taken from [this](http://www.cs.arizona.edu/classes/cs445/spring07/ShortestPath2.prn.pdf) source. 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. ![Bellman–Ford Algorithm](https://www.wikitechy.com/technology/wp-content/uploads/2017/05/Bellman%E2%80%93Ford-Algorithm.png) 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. ![C++ Programming-Bellman–Ford Algorithm](https://www.wikitechy.com/technology/wp-content/uploads/2017/05/C-Programming-Bellman%E2%80%93Ford-Algorithm.png) 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). ![C++ Programming-Bellman–Ford Algorithm](https://www.wikitechy.com/technology/wp-content/uploads/2017/05/C-Programming-Bellman%E2%80%93Ford-Algorithm-1.png) 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’t update the distances. **Phython Programming** ``` # Python program for Bellman-Ford's single source # shortest path algorithm.from collections import defaultdict#Class to represent a graph class Graph:def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = [] # default dictionary to store graph# function to add an edge to graph def addEdge(self,u,v,w): self.graph.append([u, v, w])# utility function used to print the solution def printArr(self, dist): print("Vertex Distance from Source") for i in range(self.V): print("%d \t\t %d" % (i, dist[i]))# The main function that finds shortest distances from src to # all other vertices using Bellman-Ford algorithm. The function # also detects negative weight cycle def BellmanFord(self, src):# Step 1: Initialize distances from src to all other vertices # as INFINITE dist = [float("Inf")] * self.V dist[src] = 0# Step 2: Relax all edges |V| - 1 times. A simple shortest # path from src to any other vertex can have at-most |V| - 1 # edges for i in range(self.V - 1): # Update dist value and parent index of the adjacent vertices of # the picked vertex. Consider only those vertices which are still in # queue for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: dist[v] = dist[u] + w# Step 3: check for negative-weight cycles. The above step # guarantees shortest distances if graph doesn't contain # negative weight cycle. If we get a shorter path, then there # is a cycle.for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: print "Graph contains negative weight cycle" return# print all distance self.printArr(dist)g = Graph(5) g.addEdge(0, 1, -1) g.addEdge(0, 2, 4) g.addEdge(1, 2, 3) g.addEdge(1, 3, 2) g.addEdge(1, 4, 2) g.addEdge(3, 2, 5) g.addEdge(3, 1, 1) g.addEdge(4, 3, -3)#Print the solution g.BellmanFord(0) ``` Output: - Vertex Distance from Source 0 0 1 -1 2 2 3 -2 4 1 \[ad type=”banner”\] **Notes** **1\)** 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. **2\)** Bellman-Ford works better (better than Dijksra’s) for distributed systems. Unlike Dijksra’s where we need to find minimum value of all vertices, in Bellman-Ford, edges are considered one by one. **Exercise** **1\)** 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. **2\)** Can we use Dijksra’s algorithm for shortest paths for graphs with negative weights – 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’s algorithm for the modified graph. Will this algorithm work? \[ad type=”banner”\]
Shard42 (laksa)
Root Hash6116138970510012642
Unparsed URLcom,wikitechy!www,/technology/python-programming-bellman-ford-algorithm-2/ s443