ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.8 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://medium.com/@g.shevtsov1989/bellman-ford-algorithm-in-python-8f4cbca040ac |
| Last Crawled | 2026-03-17 20:53:05 (24 days ago) |
| First Indexed | not set |
| HTTP Status Code | 200 |
| Meta Title | Bellman-Ford Algorithm in python. Introduction | by Gennadiy Shevtsov | Medium |
| Meta Description | Bellman-Ford Algorithm in python Introduction The Bellman-Ford algorithm is a well-known algorithm used to solve the single-source shortest path problem in weighted graphs. Unlike the Dijkstra … |
| Meta Canonical | null |
| Boilerpipe Text | 3 min read
Mar 19, 2023
--
Introduction
The Bellman-Ford algorithm is a well-known algorithm used to solve the single-source shortest path problem in weighted graphs. Unlike the Dijkstra algorithm, the Bellman-Ford algorithm can handle negative edge weights, and it can also detect negative weight cycles. In this article, we will discuss the Bellman-Ford algorithm in detail and implement it in Python.
Press enter or click to view image in full size
The Bellman-Ford Algorithm
The Bellman-Ford algorithm is an iterative algorithm that works by initially setting the distance to the source vertex as zero and the distance to all other vertices as infinity. Then, it iteratively relaxes the edges in the graph V-1 times, where V is the number of vertices in the graph. Relaxing an edge means checking if the distance to the destination vertex can be reduced by going through the current edge. If it can, then the distance to the destination vertex is updated.
The relaxation process reduces the distance to each vertex until it reaches the shortest path. After V-1 iterations, the algorithm checks for the presence of negative weight cycles. If a negative weight cycle is found, the algorithm returns an error indicating the presence of the cycle. If no negative weight cycles are found, the algorithm returns the shortest path from the source vertex to all other vertices in the graph.
Implementation in python
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.edges = []
def add_edge(self, u, v, weight):
self.edges.append((u, v, weight))
class BellmanFord:
def __init__(self, graph, source):
self.graph = graph
self.source = source
self.distances = {vertex: float('inf') for vertex in graph.vertices}
self.distances[source] = 0
def run(self):
for i in range(len(self.graph.vertices) - 1):
for u, v, weight in self.graph.edges:
if self.distances[u] + weight < self.distances[v]:
self.distances[v] = self.distances[u] + weight
for u, v, weight in self.graph.edges:
if self.distances[u] + weight < self.distances[v]:
print("Negative cycle detected")
return
print("Shortest distances:", self.distances)
def get_shortest_path(self, destination):
path = []
while destination != self.source:
path.append(destination)
destination = self.predecessors[destination]
path.append(self.source)
return path[::-1]
if __name__ == '__main__':
vertices = ['A', 'B', 'C', 'D', 'E']
graph = Graph(vertices)
graph.add_edge('A', 'B', 4)
graph.add_edge('A', 'C', 2)
graph.add_edge('B', 'C', 3)
graph.add_edge('B', 'D', 2)
graph.add_edge('B', 'E', 3)
graph.add_edge('C', 'B', 1)
graph.add_edge('C', 'D', 4)
graph.add_edge('C', 'E', 5)
graph.add_edge('E', 'D', 1)
bf = BellmanFord(graph, 'A')
bf.run()
print("Shortest path from A to D:", bf.get_shortest_path('D'))
In this implementation, we have a Graph class that stores the vertices and edges of the graph. The BellmanFord class takes a graph and a source vertex as input and calculates the shortest distances from the source vertex to all other vertices using the Bellman-Ford algorithm.
The run method runs the Bellman-Ford algorithm. It iterates V-1 times and relaxes each edge in each iteration. After V-1 iterations, it checks for the presence of negative weight cycles. If a negative weight cycle is detected, it prints a message indicating the presence of the cycle. Otherwise, it prints the shortest distances from the source vertex to all other vertices.
The get_shortest_path method takes a destination vertex as input and returns the shortest path from the source vertex to the destination vertex.
In the main program, we create a graph and run the Bellman-Ford algorithm on it. We print the shortest path from the source vertex to a destination vertex. |
| Markdown | [Sitemap](https://medium.com/sitemap/sitemap.xml)
[Open in app](https://play.google.com/store/apps/details?id=com.medium.reader&referrer=utm_source%3DmobileNavBar&source=post_page---top_nav_layout_nav-----------------------------------------)
Sign up
[Sign in](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Fmedium.com%2F%40g.shevtsov1989%2Fbellman-ford-algorithm-in-python-8f4cbca040ac&source=post_page---top_nav_layout_nav-----------------------global_nav------------------)
[Medium Logo](https://medium.com/?source=post_page---top_nav_layout_nav-----------------------------------------)
Get app
[Write](https://medium.com/m/signin?operation=register&redirect=https%3A%2F%2Fmedium.com%2Fnew-story&source=---top_nav_layout_nav-----------------------new_post_topnav------------------)
[Search](https://medium.com/search?source=post_page---top_nav_layout_nav-----------------------------------------)
Sign up
[Sign in](https://medium.com/m/signin?operation=login&redirect=https%3A%2F%2Fmedium.com%2F%40g.shevtsov1989%2Fbellman-ford-algorithm-in-python-8f4cbca040ac&source=post_page---top_nav_layout_nav-----------------------global_nav------------------)

# Bellman-Ford Algorithm in python
[](https://medium.com/@g.shevtsov1989?source=post_page---byline--8f4cbca040ac---------------------------------------)
[Gennadiy Shevtsov](https://medium.com/@g.shevtsov1989?source=post_page---byline--8f4cbca040ac---------------------------------------)
3 min read
·
Mar 19, 2023
\--
1
Listen
Share
**Introduction**
The Bellman-Ford algorithm is a well-known algorithm used to solve the single-source shortest path problem in weighted graphs. Unlike the Dijkstra algorithm, the Bellman-Ford algorithm can handle negative edge weights, and it can also detect negative weight cycles. In this article, we will discuss the Bellman-Ford algorithm in detail and implement it in Python.
Press enter or click to view image in full size
![]()
**The Bellman-Ford Algorithm**
The Bellman-Ford algorithm is an iterative algorithm that works by initially setting the distance to the source vertex as zero and the distance to all other vertices as infinity. Then, it iteratively relaxes the edges in the graph V-1 times, where V is the number of vertices in the graph. Relaxing an edge means checking if the distance to the destination vertex can be reduced by going through the current edge. If it can, then the distance to the destination vertex is updated.
The relaxation process reduces the distance to each vertex until it reaches the shortest path. After V-1 iterations, the algorithm checks for the presence of negative weight cycles. If a negative weight cycle is found, the algorithm returns an error indicating the presence of the cycle. If no negative weight cycles are found, the algorithm returns the shortest path from the source vertex to all other vertices in the graph.
**Implementation in python**
```
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.edges = []
def add_edge(self, u, v, weight):
self.edges.append((u, v, weight))
class BellmanFord:
def __init__(self, graph, source):
self.graph = graph
self.source = source
self.distances = {vertex: float('inf') for vertex in graph.vertices}
self.distances[source] = 0
def run(self):
for i in range(len(self.graph.vertices) - 1):
for u, v, weight in self.graph.edges:
if self.distances[u] + weight < self.distances[v]:
self.distances[v] = self.distances[u] + weight
for u, v, weight in self.graph.edges:
if self.distances[u] + weight < self.distances[v]:
print("Negative cycle detected")
return
print("Shortest distances:", self.distances)
def get_shortest_path(self, destination):
path = []
while destination != self.source:
path.append(destination)
destination = self.predecessors[destination]
path.append(self.source)
return path[::-1]
if __name__ == '__main__':
vertices = ['A', 'B', 'C', 'D', 'E']
graph = Graph(vertices)
graph.add_edge('A', 'B', 4)
graph.add_edge('A', 'C', 2)
graph.add_edge('B', 'C', 3)
graph.add_edge('B', 'D', 2)
graph.add_edge('B', 'E', 3)
graph.add_edge('C', 'B', 1)
graph.add_edge('C', 'D', 4)
graph.add_edge('C', 'E', 5)
graph.add_edge('E', 'D', 1)
bf = BellmanFord(graph, 'A')
bf.run()
print("Shortest path from A to D:", bf.get_shortest_path('D'))
```
In this implementation, we have a Graph class that stores the vertices and edges of the graph. The BellmanFord class takes a graph and a source vertex as input and calculates the shortest distances from the source vertex to all other vertices using the Bellman-Ford algorithm.
The run method runs the Bellman-Ford algorithm. It iterates V-1 times and relaxes each edge in each iteration. After V-1 iterations, it checks for the presence of negative weight cycles. If a negative weight cycle is detected, it prints a message indicating the presence of the cycle. Otherwise, it prints the shortest distances from the source vertex to all other vertices.
The get\_shortest\_path method takes a destination vertex as input and returns the shortest path from the source vertex to the destination vertex.
In the main program, we create a graph and run the Bellman-Ford algorithm on it. We print the shortest path from the source vertex to a destination vertex.
[Algorithms](https://medium.com/tag/algorithms?source=post_page-----8f4cbca040ac---------------------------------------)
[Education](https://medium.com/tag/education?source=post_page-----8f4cbca040ac---------------------------------------)
[Python](https://medium.com/tag/python?source=post_page-----8f4cbca040ac---------------------------------------)
[Programming](https://medium.com/tag/programming?source=post_page-----8f4cbca040ac---------------------------------------)
[Coding](https://medium.com/tag/coding?source=post_page-----8f4cbca040ac---------------------------------------)
\--
\--
1
[](https://medium.com/@g.shevtsov1989?source=post_page---post_author_info--8f4cbca040ac---------------------------------------)
[](https://medium.com/@g.shevtsov1989?source=post_page---post_author_info--8f4cbca040ac---------------------------------------)
[Written by Gennadiy Shevtsov](https://medium.com/@g.shevtsov1989?source=post_page---post_author_info--8f4cbca040ac---------------------------------------)
[6\.9K followers](https://medium.com/@g.shevtsov1989/followers?source=post_page---post_author_info--8f4cbca040ac---------------------------------------)
·[30K following](https://medium.com/@g.shevtsov1989/following?source=post_page---post_author_info--8f4cbca040ac---------------------------------------)
My journey through the realms of programming has led me to establish a dynamic digital haven:<https://omniscopelife.com/>
## Responses (1)
See all responses
[Help](https://help.medium.com/hc/en-us?source=post_page-----8f4cbca040ac---------------------------------------)
[Status](https://status.medium.com/?source=post_page-----8f4cbca040ac---------------------------------------)
[About](https://medium.com/about?autoplay=1&source=post_page-----8f4cbca040ac---------------------------------------)
[Careers](https://medium.com/jobs-at-medium/work-at-medium-959d1a85284e?source=post_page-----8f4cbca040ac---------------------------------------)
[Press](mailto:pressinquiries@medium.com)
[Blog](https://blog.medium.com/?source=post_page-----8f4cbca040ac---------------------------------------)
[Privacy](https://policy.medium.com/medium-privacy-policy-f03bf92035c9?source=post_page-----8f4cbca040ac---------------------------------------)
[Rules](https://policy.medium.com/medium-rules-30e5502c4eb4?source=post_page-----8f4cbca040ac---------------------------------------)
[Terms](https://policy.medium.com/medium-terms-of-service-9db0094a1e0f?source=post_page-----8f4cbca040ac---------------------------------------)
[Text to speech](https://speechify.com/medium?source=post_page-----8f4cbca040ac---------------------------------------) |
| Readable Markdown | [](https://medium.com/@g.shevtsov1989?source=post_page---byline--8f4cbca040ac---------------------------------------)
3 min read Mar 19, 2023
\--
**Introduction**
The Bellman-Ford algorithm is a well-known algorithm used to solve the single-source shortest path problem in weighted graphs. Unlike the Dijkstra algorithm, the Bellman-Ford algorithm can handle negative edge weights, and it can also detect negative weight cycles. In this article, we will discuss the Bellman-Ford algorithm in detail and implement it in Python.
Press enter or click to view image in full size
**The Bellman-Ford Algorithm**
The Bellman-Ford algorithm is an iterative algorithm that works by initially setting the distance to the source vertex as zero and the distance to all other vertices as infinity. Then, it iteratively relaxes the edges in the graph V-1 times, where V is the number of vertices in the graph. Relaxing an edge means checking if the distance to the destination vertex can be reduced by going through the current edge. If it can, then the distance to the destination vertex is updated.
The relaxation process reduces the distance to each vertex until it reaches the shortest path. After V-1 iterations, the algorithm checks for the presence of negative weight cycles. If a negative weight cycle is found, the algorithm returns an error indicating the presence of the cycle. If no negative weight cycles are found, the algorithm returns the shortest path from the source vertex to all other vertices in the graph.
**Implementation in python**
```
class Graph:
def __init__(self, vertices):
self.vertices = vertices
self.edges = [] def add_edge(self, u, v, weight):
self.edges.append((u, v, weight)) class BellmanFord:
def __init__(self, graph, source):
self.graph = graph
self.source = source
self.distances = {vertex: float('inf') for vertex in graph.vertices}
self.distances[source] = 0 def run(self):
for i in range(len(self.graph.vertices) - 1):
for u, v, weight in self.graph.edges:
if self.distances[u] + weight < self.distances[v]:
self.distances[v] = self.distances[u] + weight for u, v, weight in self.graph.edges:
if self.distances[u] + weight < self.distances[v]:
print("Negative cycle detected")
return print("Shortest distances:", self.distances) def get_shortest_path(self, destination):
path = []
while destination != self.source:
path.append(destination)
destination = self.predecessors[destination]
path.append(self.source)
return path[::-1] if __name__ == '__main__':
vertices = ['A', 'B', 'C', 'D', 'E']
graph = Graph(vertices)
graph.add_edge('A', 'B', 4)
graph.add_edge('A', 'C', 2)
graph.add_edge('B', 'C', 3)
graph.add_edge('B', 'D', 2)
graph.add_edge('B', 'E', 3)
graph.add_edge('C', 'B', 1)
graph.add_edge('C', 'D', 4)
graph.add_edge('C', 'E', 5)
graph.add_edge('E', 'D', 1) bf = BellmanFord(graph, 'A')
bf.run()
print("Shortest path from A to D:", bf.get_shortest_path('D'))
```
In this implementation, we have a Graph class that stores the vertices and edges of the graph. The BellmanFord class takes a graph and a source vertex as input and calculates the shortest distances from the source vertex to all other vertices using the Bellman-Ford algorithm.
The run method runs the Bellman-Ford algorithm. It iterates V-1 times and relaxes each edge in each iteration. After V-1 iterations, it checks for the presence of negative weight cycles. If a negative weight cycle is detected, it prints a message indicating the presence of the cycle. Otherwise, it prints the shortest distances from the source vertex to all other vertices.
The get\_shortest\_path method takes a destination vertex as input and returns the shortest path from the source vertex to the destination vertex.
In the main program, we create a graph and run the Bellman-Ford algorithm on it. We print the shortest path from the source vertex to a destination vertex. |
| Shard | 77 (laksa) |
| Root Hash | 13179037029838926277 |
| Unparsed URL | com,medium!/@g.shevtsov1989/bellman-ford-algorithm-in-python-8f4cbca040ac s443 |