🕷️ Crawler Inspector

URL Lookup

Direct Parameter Lookup

Raw Queries and Responses

1. Shard Calculation

Query:
Response:
Calculated Shard: 131 (from laksa115)

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
2 days ago
🤖
ROBOTS ALLOWED

Page Info Filters

FilterStatusConditionDetails
HTTP statusPASSdownload_http_code = 200HTTP 200
Age cutoffPASSdownload_stamp > now() - 6 MONTH0.1 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://favtutor.com/blogs/bellman-ford-python
Last Crawled2026-04-08 14:43:18 (2 days ago)
First Indexed2021-06-09 11:44:02 (4 years ago)
HTTP Status Code200
Meta TitleBellman Ford Algorithm in Python (Example with Code)
Meta DescriptionUnderstand bellman ford algorithm step by step along with the example and Python code. Also, what is the time complexity of the algorithm?
Meta Canonicalnull
Boilerpipe Text
Bellman-Ford algorithm stands as a fundamental tool for finding the shortest paths between nodes. Richard Bellman and Lester Ford Jr. founded this algorithm has found applications in computer science. In this article, we will study the Bellman-Ford algorithm along with its code in Python. We will also find its time complexity. What is Bellman-Ford Algorithm? Bellman-Ford algorithm is used to find the shortest path from the source vertex to every vertex in a weighted graph. Unlike Dijkstra's algorithm , the Bbellman-Ford algorithm can also find the shortest distance to every vertex in the weighted graph even with the negative edges. The only difference between the Dijkstra algorithm and the bellman ford algorithm is that Dijkstra's algorithm just visits the neighbor vertex in each iteration but the bellman ford algorithm visits each vertex through each edge in every iteration. Apart from Bellman-Ford and Dijkstra's, Floyd Warshall Algorithm is also the shortest path algorithm. But the Bellman-Ford algorithm is used to compute the shortest path from the single source vertex to all other vertices whereas Floyd-Warshall algorithms compute the shortest path from each node to every other node. Here is the simple algorithm: Begin    count : = 1    maxEdge : = a * (a - 1 ) / 2     // a is number of vertices     for all vertices n of the graph, do       distance[n] : = ∞       pred[n] : = ?    done    distance[source] : = 0    eCount : = number of edges in the graph    create edge list named edgeList     while count < a, do        for k : = 0 to eCount, do           if distance[edgeList[k] . n] > distance[edgeList[k] . m] + (cost[m,n] for edge k) distance[edgeList[k] . n] > distance[edgeList[k] . m] + (cost[m,n] for edge k) pred[edgeList[k] . n] : = edgeList[k] . m       done    done    count : = count + 1     for all vertices k in the graph, do        if distance[edgeList[k] . n] > distance[edgeList[k] . m] + (cost[m,n] for edge k),          then return true    done     return false End Let's look at it step-by-step to understand the Bellman-Ford algorithm: Initializing the source vertex with distance to itself as 0 and all other vertices as infinity. Creating the array with size N. Calculate the shortest distance from the source vertex. Following this process for N-1 times where N is the number of vertices in the graph. For relaxing the path lengths for the vertices for each edge m-n: if distance[n] > distance[m] + weight of edge mn, then distance[n] = distance[m] + weight of edge mn Even after minimizing the path lengths for each vertex after N-1 times, if we can still relax the path length where distance[n] > distance[m] + weight of edge mn then we can say that the graph contains the negative edge cycle. Bellman-Ford algorithm follows the dynamic programming approach by overestimating the length of the path from the starting vertex to all other vertices. And then it starts relaxing the estimates by discovering the new paths which are shorter than the previous ones. This process is followed by all the vertices for N-1 times for finding the optimized result.  Bellman-Ford Algorithm Example Consider the following weighted graph: Select the source vertex with path value 0 and all other vertices as infinity. Visit the neighboring edge from the source vertex and relax the path length of the neighboring vertex if the newly calculated path length is smaller than the previous path length This process must be followed N-1 times where N is the total number of vertices. This is because in the worst-case scenario, any vertex’s path length can be changed to an even smaller path length for N times. Therefore after N-1 iterations, we find our new path lengths and we can check if the graph has a negative cycle or not. Look at the following pseudocode: function bellmanFord(G, S)    for each vertex N in G     distance[N] <- infinite       previous[N] <- NULL   distance[S] <- 0    for each vertex N in G      for each edge (M,N) in G       tempDistance <- distance[M] + edge_weight(M, N)        if tempDistance < distance[N]         distance[N] <- tempDistance         previous[N] <- M    for each edge (M,N) in G     If distance[M] + edge_weight(M, N) < distance[N}       Error: Negative Cycle Exists    return distance[], previous[] We maintain the path length of every vertex and store that in an array with a size N where N is the number of vertices. After the algorithm is over we will backtrack from the last vertex to the source vertex to find the path. Python Code for Bellman-Ford Algorithm Here is the full source code to implement the Bellman-Ford algorithm in Python: class Graph :      def __init__ ( self , vertices):          self . M = vertices   # Total number of vertices in the graph          self . graph = []     # Array of edges      # Add edges      def add_edge ( self , a, b, c):          self . graph . append([a, b, c])      # Print the solution      def print_solution ( self , distance):          print ( "Vertex Distance from Source" )          for k in range ( self . M):              print ( "{0} \t\t {1}" . format(k, distance[k]))      def bellman_ford ( self , src):         distance = [ float ( "Inf" )] * self . M         distance[src] = 0          for _ in range ( self . M - 1 ):              for a, b, c in self . graph:                  if distance[a] != float ( "Inf" ) and distance[a] + c < distance[b]:                     distance[b] = distance[a] + c          for a, b, c in self . graph:              if distance[a] != float ( "Inf" ) and distance[a] + c < distance[b]:                  print ( "Graph contains negative weight cycle" )                  return          self . print_solution(distance) g = Graph( 5 ) g . add_edge( 0 , 1 , 2 ) g . add_edge( 0 , 2 , 4 ) g . add_edge( 1 , 3 , 2 ) g . add_edge( 2 , 4 , 3 ) g . add_edge( 2 , 3 , 4 ) g . add_edge( 4 , 3 , - 5 ) g . bellman_ford( 0 ) Output: Vertex Distance from Source 0 0 1 2 2 4 3 2 4 7 Time Complexity The time complexity of the bellman ford algorithm for the best case is O(E) while average-case and worst-case time complexity are O(NE) where N is the number of vertices and E is the total edges to be relaxed. Also, the space complexity of the Bellman-Ford algorithm is O(N) because the size of the array is N. Is Bellman-Ford better than Dijkstra? Like everything else, Bellman-Ford and Dijkstra have their own use cases and pros and cons. The Bellman-Ford algorithm is better in cases where the graph contains non-negative weighted edges. It is designed to handle negative weight edges and can detect negative weight cycles. This method has a way of handling negative weight edges, but it has a higher time complexity of O(|V|*|E|), where |V| is the number of vertices and |E| is the number of edges.  However, in terms of time complexity, Bellman-Ford is less efficient. On the other hand, for a graph with non-negative edge weights, Dijkstra’s algorithm is a better choice, because it is faster and has better time efficiency. Its time complexity is O((|V| + |E|)log|V|) when using a binary heap priority queue or O(|V|^2) when using a simple array. Dijkstra’s algorithm is more time efficient because it discards all the paths which are not optimal, ensuring that it takes the shortest possible path. Where does the Bellman-Ford algorithm fail? The main purpose of this algorithm is to find the shortest possible path. The presence of a negative-weight cycle can cause the Bellman-Ford algorithm to fail. A negative weight cycle is a cycle in the graph that sums up to a negative weight when the weights of all its edges are added up. Another case would be if the given graph has no edges since the Bellman-Ford algorithm relies solely on the edges to determine the shortest path. If the graph is a disconnected graph, i.e., if there are no nodes connecting two vertices, the algorithm will malfunction. Conclusion In the above article, we studied what is Bellman-Ford algorithm, and understood the Bellman-Ford algorithm step by step along with the example. We further learned Python code and the corresponding output for finding the distance from the source vertex in a weighted graph.
Markdown
- [support@favtutor.com]() - [Sign in](https://students.favtutor.com/) - [Sign up](https://students.favtutor.com/memberSignup) [![FavTutor](https://favtutor.com/resources/images/logo.png)](https://favtutor.com/) - [Live Tutors](https://favtutor.com/blogs/bellman-ford-python) - [R Tutors](https://favtutor.com/r-tutor) - [Python Tutors](https://favtutor.com/python-tutors) - [Java Tutors](https://favtutor.com/java-programming-tutors) - [DSA Tutors](https://favtutor.com/data-structures-tutors) - [SQL Tutors](https://favtutor.com/sql-tutors) - [Machine Learning Tutors](https://favtutor.com/machine-learning-tutor) - [LeetCode Tutors](https://favtutor.com/leetcode-tutors) - [How It Works](https://favtutor.com/how-it-work) - [Pricing](https://favtutor.com/pricing) - [AI Mock Interview](https://favtutor.com/ai-mock-interview) - [Learn](https://favtutor.com/blogs/bellman-ford-python) - [**Blog** A comprehensive collection of coding resources and knowledge](https://favtutor.com/blogs) - [**Articles** Latest Coding News and In-Depth Tutorials](https://favtutor.com/articles) - [Tools NEW](https://favtutor.com/blogs/bellman-ford-python) - [Learn with AI](https://ailearning.favtutor.com/) - [AI Code Generator](https://favtutor.com/ai-code-generator) - [AI Code Debugger](https://favtutor.com/ai-code-debugger) - [AI Data Analysis](https://favtutor.com/ai-data-analysis) - [AI Code Converter](https://favtutor.com/ai-code-converter) - [Sign In/Sign Up](https://students.favtutor.com/) [Get Help Now](https://students.favtutor.com/memberSignup) ![](https://favtutor.com/resources/images/model-img.png) What’s New ? ### The Top 10 favtutor Features You Might Have Overlooked [Read More](https://favtutor.com/blogs/bellman-ford-python) - [![FavTutor](https://favtutor.com/resources/images/logo.png)](https://favtutor.com/) - Don’t have an account Yet? [Sign Up](https://favtutor.com/blogs/bellman-ford-python#0) - [![FavTutor](https://favtutor.com/resources/images/logo.png)](https://favtutor.com/) - Already have an Account? [Sign In](https://favtutor.com/blogs/bellman-ford-python#0) - [![FavTutor](https://favtutor.com/resources/images/logo.png)](https://favtutor.com/) - Don’t have an account Yet? [Sign Up](https://favtutor.com/blogs/bellman-ford-python#0) Lost your password? Please enter your email address. You will receive a link to create a new password. [Back to log-in](https://favtutor.com/blogs/bellman-ford-python#0) By Signing up for Favtutor, you agree to our [Terms of Service](https://favtutor.com/terms) & [Privacy Policy.](https://favtutor.com/privacy) [Close](https://favtutor.com/blogs/bellman-ford-python#0) # Bellman Ford Algorithm in Python (Example with Code) - Jun 10, 2023 - 7 Minutes Read - Why Trust Us We uphold a strict [editorial policy](https://favtutor.com/editorial-policy) that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing. - [By Shivali Bhadaniya](https://favtutor.com/blogs/bellman-ford-python#blogInfo) ![ Bellman Ford Algorithm in Python (Example with Code) ](https://favtutor.com/resources/images/uploads/bellman_ford_algorithm.png) Bellman-Ford algorithm stands as a fundamental tool for finding the shortest paths between nodes. Richard Bellman and Lester Ford Jr. founded this algorithm has found applications in computer science. In this article, we will study the Bellman-Ford algorithm along with its code in Python. We will also find its time complexity. ## **What is Bellman-Ford Algorithm?** **Bellman-Ford algorithm is used to find the shortest path from the source vertex to every vertex in a weighted graph.** Unlike [Dijkstra's algorithm](https://favtutor.com/blogs/dijkstras-algorithm-cpp), the Bbellman-Ford algorithm can also find the shortest distance to every vertex in the weighted graph even with the negative edges. The only difference between the Dijkstra algorithm and the bellman ford algorithm is that Dijkstra's algorithm just visits the neighbor vertex in each iteration but the bellman ford algorithm visits each vertex through each edge in every iteration. Apart from Bellman-Ford and Dijkstra's, [Floyd Warshall Algorithm](https://favtutor.com/blogs/floyd-warshall-algorithm) is also the shortest path algorithm. But the Bellman-Ford algorithm is used to compute the shortest path from the single source vertex to all other vertices whereas Floyd-Warshall algorithms compute the shortest path from each node to every other node. Here is the simple algorithm: ``` Begin    count := 1    maxEdge := a * (a - 1) / 2     //a is number of vertices    for all vertices n of the graph, do       distance[n] := ∞       pred[n] := ?    done    distance[source] := 0    eCount := number of edges in the graph    create edge list named edgeList    while count < a, do       for k := 0 to eCount, do          if distance[edgeList[k].n] > distance[edgeList[k].m] + (cost[m,n] for edge k) distance[edgeList[k].n] > distance[edgeList[k].m] + (cost[m,n] for edge k) pred[edgeList[k].n] := edgeList[k].m       done    done    count := count + 1    for all vertices k in the graph, do       if distance[edgeList[k].n] > distance[edgeList[k].m] + (cost[m,n] for edge k),          then return true    done    return false End ``` Let's look at it step-by-step to understand the Bellman-Ford algorithm: 1. Initializing the source vertex with distance to itself as 0 and all other vertices as infinity. Creating the array with size N. 2. Calculate the shortest distance from the source vertex. Following this process for N-1 times where N is the number of vertices in the graph. 1. For relaxing the path lengths for the vertices for each edge m-n: 2. if distance\[n\] \> distance\[m\] + weight of edge mn, then 3. distance\[n\] = distance\[m\] + weight of edge mn 3. Even after minimizing the path lengths for each vertex after N-1 times, if we can still relax the path length where distance\[n\] \> distance\[m\] + weight of edge mn then we can say that the graph contains the negative edge cycle. Bellman-Ford algorithm follows the [dynamic programming](https://favtutor.com/blogs/dynamic-programming "Dynamic Programming (With Python Problems)") approach by overestimating the length of the path from the starting vertex to all other vertices. And then it starts relaxing the estimates by discovering the new paths which are shorter than the previous ones. This process is followed by all the vertices for N-1 times for finding the optimized result. ### **Bellman-Ford Algorithm Example** Consider the following weighted graph: ![bellman ford example](https://favtutor.com/resources/images/uploads/mceu_29744780111623235472600.png) Select the source vertex with path value 0 and all other vertices as infinity. ![selecting the source vertex](https://favtutor.com/resources/images/uploads/mceu_68241409821623235499159.png) Visit the neighboring edge from the source vertex and relax the path length of the neighboring vertex if the newly calculated path length is smaller than the previous path length ![visiting the neighbouring edge](https://favtutor.com/resources/images/uploads/mceu_4758547131623235534321.png) This process must be followed N-1 times where N is the total number of vertices. This is because in the worst-case scenario, any vertex’s path length can be changed to an even smaller path length for N times. ![bellman ford time run complexity](https://favtutor.com/resources/images/uploads/mceu_51910454441623235547334.png) Therefore after N-1 iterations, we find our new path lengths and we can check if the graph has a negative cycle or not. ![final output of bellman ford ](https://favtutor.com/resources/images/uploads/mceu_74845339451623235563432.png) Look at the following pseudocode: ``` function bellmanFord(G, S)   for each vertex N in G     distance[N] <- infinite       previous[N] <- NULL   distance[S] <- 0   for each vertex N in G     for each edge (M,N) in G       tempDistance <- distance[M] + edge_weight(M, N)       if tempDistance < distance[N]         distance[N] <- tempDistance         previous[N] <- M   for each edge (M,N) in G     If distance[M] + edge_weight(M, N) < distance[N}       Error: Negative Cycle Exists   return distance[], previous[] ``` We maintain the path length of every vertex and store that in an array with a size N where N is the number of vertices. After the algorithm is over we will backtrack from the last vertex to the source vertex to find the path. ### **Python Code for Bellman-Ford Algorithm** Here is the full source code to implement the Bellman-Ford algorithm in Python: ``` class Graph:     def __init__(self, vertices):         self.M = vertices   # Total number of vertices in the graph         self.graph = []     # Array of edges     # Add edges     def add_edge(self, a, b, c):         self.graph.append([a, b, c])     # Print the solution     def print_solution(self, distance):         print("Vertex Distance from Source")         for k in range(self.M):             print("{0}\t\t{1}".format(k, distance[k]))     def bellman_ford(self, src):         distance = [float("Inf")] * self.M         distance[src] = 0         for _ in range(self.M - 1):             for a, b, c in self.graph:                 if distance[a] != float("Inf") and distance[a] + c < distance[b]:                     distance[b] = distance[a] + c         for a, b, c in self.graph:             if distance[a] != float("Inf") and distance[a] + c < distance[b]:                 print("Graph contains negative weight cycle")                 return         self.print_solution(distance) g = Graph(5) g.add_edge(0, 1, 2) g.add_edge(0, 2, 4) g.add_edge(1, 3, 2) g.add_edge(2, 4, 3) g.add_edge(2, 3, 4) g.add_edge(4, 3, -5) g.bellman_ford(0) ``` ### **Output:** ``` Vertex Distance from Source 0 0 1 2 2 4 3 2 4 7 ``` ## ### **Time Complexity** **The time complexity of the bellman ford algorithm for the best case is O(E) while average-case and worst-case time complexity are O(NE) where N is the number of vertices and E is the total edges to be relaxed.** Also, the space complexity of the Bellman-Ford algorithm is O(N) because the size of the array is N. ### **Is Bellman-Ford better than Dijkstra?** Like everything else, Bellman-Ford and Dijkstra have their own use cases and pros and cons. **The Bellman-Ford algorithm is better in cases where the graph contains non-negative weighted edges.** It is designed to handle negative weight edges and can detect negative weight cycles. This method has a way of handling negative weight edges, but it has a higher time complexity of O(\|V\|\*\|E\|), where \|V\| is the number of vertices and \|E\| is the number of edges. However, in terms of time complexity, Bellman-Ford is less efficient. On the other hand, for a graph with non-negative edge weights, Dijkstra’s algorithm is a better choice, because it is faster and has better time efficiency. Its time complexity is O((\|V\| + \|E\|)log\|V\|) when using a binary heap priority queue or O(\|V\|^2) when using a simple array. Dijkstra’s algorithm is more time efficient because it discards all the paths which are not optimal, ensuring that it takes the shortest possible path. ### **Where does the Bellman-Ford algorithm fail?** The main purpose of this algorithm is to find the shortest possible path. **The presence of a negative-weight cycle can cause the Bellman-Ford algorithm to fail.** A negative weight cycle is a cycle in the graph that sums up to a negative weight when the weights of all its edges are added up. Another case would be if the given graph has no edges since the Bellman-Ford algorithm relies solely on the edges to determine the shortest path. If the graph is a disconnected graph, i.e., if there are no nodes connecting two vertices, the algorithm will malfunction. ## **Conclusion** In the above article, we studied what is Bellman-Ford algorithm, and understood the Bellman-Ford algorithm step by step along with the example. We further learned Python code and the corresponding output for finding the distance from the source vertex in a weighted graph. ![](https://favtutor.com/resources/images/bdf1.png) ### FavTutor - 24x7 Live Coding Help from Expert Tutors\! [Get Help Now](https://students.favtutor.com/memberSignup) ![](https://favtutor.com/resources/images/bdf2.png) ##### About The Author ![](https://favtutor.com/resources/images/uploads/Author_Shivali.jpg) ###### Shivali Bhadaniya "I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds." #### More by FavTutor Blogs ##### [Reverse Level Order Traversal in Binary Tree (with code)](https://favtutor.com/blogs/reverse-level-order-traversal) ###### Vedanti Kshirsagar [![](https://favtutor.com/resources/images/uploads/Reverse_Level_Order_Traversal_feature_image.jpg)](https://favtutor.com/blogs/reverse-level-order-traversal) ##### [Types of Inheritance in Python (with Examples)](https://favtutor.com/blogs/types-of-inheritance-python) ###### Kusum Jain [![](https://favtutor.com/resources/images/uploads/Types_of_Inheritance_in_Python_Feature_Image.jpg)](https://favtutor.com/blogs/types-of-inheritance-python) ##### [What does xrange() do in Python?](https://favtutor.com/blogs/xrange-python) ###### Kusum Jain [![](https://favtutor.com/resources/images/uploads/xrange_python_feature_image.jpg)](https://favtutor.com/blogs/xrange-python) ##### Important Subjects - [Computer Science Help](https://favtutor.com/computer-science) - [Data Science Help](https://favtutor.com/data-science) - [Programming Help](https://favtutor.com/programming-help) - [Statistics Help](https://favtutor.com/statistics-help) - [Java Homework Help](https://favtutor.com/java-homework-help) - [Python Assignment Help](https://favtutor.com/python-assignment-help) - [Tableau Assignment Help](https://favtutor.com/tableau-assignment-help) - [SAS Assignment Help](https://favtutor.com/sas-assignment-help) - [Vue.js Expert Help](https://favtutor.com/vue-assignment-help) ##### Important Subjects - [Excel Help](https://favtutor.com/excel-help) - [Deep Learning Help](https://favtutor.com/deep-learning-help) - [Machine Learning Help](https://favtutor.com/machine-learning-help) - [Data Structures Help](https://favtutor.com/data-structures-assignment-help) - [Data Mining Help](https://favtutor.com/data-mining-assignment-help) - [SQL Help](https://favtutor.com/sql-assignment-help) - [Power BI Assignment Help](https://favtutor.com/power-bi-assignment-help) - [ReactJS Homework Help](https://favtutor.com/react-assignment-help) - [CCNA Assignment Help](https://favtutor.com/ccna-assignment-help) ##### Important Subjects - [Data Analysis Help](https://favtutor.com/data-analysis-help) - [C Programming Help](https://favtutor.com/c-programming-help) - [C++ Help](https://favtutor.com/cpp-homework-help) - [Html Help](https://favtutor.com/html-homework-help) - [Android Help](https://favtutor.com/android-help) - [R programming Help](https://favtutor.com/r-homework-help) - [SPSS Assignment Help](https://favtutor.com/spss-assignment-help) - [Angular Assignment Help](https://favtutor.com/angular-assignment-help) - [Django Homework Help](https://favtutor.com/django-assignment-help) ##### Reach Out To Us - \+1(786) 231-3819 - support@favtutor.com ![FavTutor](https://favtutor.com/resources/images/footer_logo.png) - [Home](https://favtutor.com/) - [About](https://favtutor.com/about) - [How It Work](https://favtutor.com/how-it-work) - [Pricing](https://favtutor.com/pricing) - [Blogs](https://favtutor.com/blogs) - [Contact](https://favtutor.com/contact) - [Faq](https://favtutor.com/faq) - [New Articles](https://favtutor.com/articles) - [Terms & Conditions](https://favtutor.com/terms) - [Privacy Policy](https://favtutor.com/privacy) - [Editorial Policy](https://favtutor.com/editorial-policy) - [Become a Tutor](https://favtutor.com/become-a-tutor) Website listed on [Ecomswap](https://ecomswap.io/). © Copyright 2025. All Rights Reserved.
Readable Markdown
Bellman-Ford algorithm stands as a fundamental tool for finding the shortest paths between nodes. Richard Bellman and Lester Ford Jr. founded this algorithm has found applications in computer science. In this article, we will study the Bellman-Ford algorithm along with its code in Python. We will also find its time complexity. ## **What is Bellman-Ford Algorithm?** **Bellman-Ford algorithm is used to find the shortest path from the source vertex to every vertex in a weighted graph.** Unlike [Dijkstra's algorithm](https://favtutor.com/blogs/dijkstras-algorithm-cpp), the Bbellman-Ford algorithm can also find the shortest distance to every vertex in the weighted graph even with the negative edges. The only difference between the Dijkstra algorithm and the bellman ford algorithm is that Dijkstra's algorithm just visits the neighbor vertex in each iteration but the bellman ford algorithm visits each vertex through each edge in every iteration. Apart from Bellman-Ford and Dijkstra's, [Floyd Warshall Algorithm](https://favtutor.com/blogs/floyd-warshall-algorithm) is also the shortest path algorithm. But the Bellman-Ford algorithm is used to compute the shortest path from the single source vertex to all other vertices whereas Floyd-Warshall algorithms compute the shortest path from each node to every other node. Here is the simple algorithm: ``` Begin    count := 1    maxEdge := a * (a - 1) / 2     //a is number of vertices    for all vertices n of the graph, do       distance[n] := ∞       pred[n] := ?    done    distance[source] := 0    eCount := number of edges in the graph    create edge list named edgeList    while count < a, do       for k := 0 to eCount, do          if distance[edgeList[k].n] > distance[edgeList[k].m] + (cost[m,n] for edge k) distance[edgeList[k].n] > distance[edgeList[k].m] + (cost[m,n] for edge k) pred[edgeList[k].n] := edgeList[k].m       done    done    count := count + 1    for all vertices k in the graph, do       if distance[edgeList[k].n] > distance[edgeList[k].m] + (cost[m,n] for edge k),          then return true    done    return false End ``` Let's look at it step-by-step to understand the Bellman-Ford algorithm: 1. Initializing the source vertex with distance to itself as 0 and all other vertices as infinity. Creating the array with size N. 2. Calculate the shortest distance from the source vertex. Following this process for N-1 times where N is the number of vertices in the graph. 1. For relaxing the path lengths for the vertices for each edge m-n: 2. if distance\[n\] \> distance\[m\] + weight of edge mn, then 3. distance\[n\] = distance\[m\] + weight of edge mn 3. Even after minimizing the path lengths for each vertex after N-1 times, if we can still relax the path length where distance\[n\] \> distance\[m\] + weight of edge mn then we can say that the graph contains the negative edge cycle. Bellman-Ford algorithm follows the [dynamic programming](https://favtutor.com/blogs/dynamic-programming "Dynamic Programming (With Python Problems)") approach by overestimating the length of the path from the starting vertex to all other vertices. And then it starts relaxing the estimates by discovering the new paths which are shorter than the previous ones. This process is followed by all the vertices for N-1 times for finding the optimized result. ### **Bellman-Ford Algorithm Example** Consider the following weighted graph: ![bellman ford example](https://favtutor.com/resources/images/uploads/mceu_29744780111623235472600.png) Select the source vertex with path value 0 and all other vertices as infinity. ![selecting the source vertex](https://favtutor.com/resources/images/uploads/mceu_68241409821623235499159.png) Visit the neighboring edge from the source vertex and relax the path length of the neighboring vertex if the newly calculated path length is smaller than the previous path length ![visiting the neighbouring edge](https://favtutor.com/resources/images/uploads/mceu_4758547131623235534321.png) This process must be followed N-1 times where N is the total number of vertices. This is because in the worst-case scenario, any vertex’s path length can be changed to an even smaller path length for N times. ![bellman ford time run complexity](https://favtutor.com/resources/images/uploads/mceu_51910454441623235547334.png) Therefore after N-1 iterations, we find our new path lengths and we can check if the graph has a negative cycle or not. ![final output of bellman ford ](https://favtutor.com/resources/images/uploads/mceu_74845339451623235563432.png) Look at the following pseudocode: ``` function bellmanFord(G, S)   for each vertex N in G     distance[N] <- infinite       previous[N] <- NULL   distance[S] <- 0   for each vertex N in G     for each edge (M,N) in G       tempDistance <- distance[M] + edge_weight(M, N)       if tempDistance < distance[N]         distance[N] <- tempDistance         previous[N] <- M   for each edge (M,N) in G     If distance[M] + edge_weight(M, N) < distance[N}       Error: Negative Cycle Exists   return distance[], previous[] ``` We maintain the path length of every vertex and store that in an array with a size N where N is the number of vertices. After the algorithm is over we will backtrack from the last vertex to the source vertex to find the path. ### **Python Code for Bellman-Ford Algorithm** Here is the full source code to implement the Bellman-Ford algorithm in Python: ``` class Graph:     def __init__(self, vertices):         self.M = vertices   # Total number of vertices in the graph         self.graph = []     # Array of edges     # Add edges     def add_edge(self, a, b, c):         self.graph.append([a, b, c])     # Print the solution     def print_solution(self, distance):         print("Vertex Distance from Source")         for k in range(self.M):             print("{0}\t\t{1}".format(k, distance[k]))     def bellman_ford(self, src):         distance = [float("Inf")] * self.M         distance[src] = 0         for _ in range(self.M - 1):             for a, b, c in self.graph:                 if distance[a] != float("Inf") and distance[a] + c < distance[b]:                     distance[b] = distance[a] + c         for a, b, c in self.graph:             if distance[a] != float("Inf") and distance[a] + c < distance[b]:                 print("Graph contains negative weight cycle")                 return         self.print_solution(distance) g = Graph(5) g.add_edge(0, 1, 2) g.add_edge(0, 2, 4) g.add_edge(1, 3, 2) g.add_edge(2, 4, 3) g.add_edge(2, 3, 4) g.add_edge(4, 3, -5) g.bellman_ford(0) ``` **Output:** ``` Vertex Distance from Source 0 0 1 2 2 4 3 2 4 7 ``` ### **Time Complexity** **The time complexity of the bellman ford algorithm for the best case is O(E) while average-case and worst-case time complexity are O(NE) where N is the number of vertices and E is the total edges to be relaxed.** Also, the space complexity of the Bellman-Ford algorithm is O(N) because the size of the array is N. ### **Is Bellman-Ford better than Dijkstra?** Like everything else, Bellman-Ford and Dijkstra have their own use cases and pros and cons. **The Bellman-Ford algorithm is better in cases where the graph contains non-negative weighted edges.** It is designed to handle negative weight edges and can detect negative weight cycles. This method has a way of handling negative weight edges, but it has a higher time complexity of O(\|V\|\*\|E\|), where \|V\| is the number of vertices and \|E\| is the number of edges. However, in terms of time complexity, Bellman-Ford is less efficient. On the other hand, for a graph with non-negative edge weights, Dijkstra’s algorithm is a better choice, because it is faster and has better time efficiency. Its time complexity is O((\|V\| + \|E\|)log\|V\|) when using a binary heap priority queue or O(\|V\|^2) when using a simple array. Dijkstra’s algorithm is more time efficient because it discards all the paths which are not optimal, ensuring that it takes the shortest possible path. ### **Where does the Bellman-Ford algorithm fail?** The main purpose of this algorithm is to find the shortest possible path. **The presence of a negative-weight cycle can cause the Bellman-Ford algorithm to fail.** A negative weight cycle is a cycle in the graph that sums up to a negative weight when the weights of all its edges are added up. Another case would be if the given graph has no edges since the Bellman-Ford algorithm relies solely on the edges to determine the shortest path. If the graph is a disconnected graph, i.e., if there are no nodes connecting two vertices, the algorithm will malfunction. ## **Conclusion** In the above article, we studied what is Bellman-Ford algorithm, and understood the Bellman-Ford algorithm step by step along with the example. We further learned Python code and the corresponding output for finding the distance from the source vertex in a weighted graph.
Shard131 (laksa)
Root Hash1162696084485777131
Unparsed URLcom,favtutor!/blogs/bellman-ford-python s443