Bellman-Ford algorithm in Python
Last Updated :
08 Mar, 2025
Given a weighted graph with V vertices and E edges, and a source vertex src, find the shortest path from the source vertex to all vertices in the given graph. If a vertex cannot be reached from source vertex, mark its distance as 108.
Note: If a graph contains negative weight cycle, return -1.
Bellman-Ford is a single source shortest path algorithm. It effectively works in the cases of negative edges and is able to detect negative cycles as well. It works on the principle of relaxation of the edges.
Examples:
Input: V = 5, edges = [[1, 3, 2], [4, 3, -1], [2, 4, 1], [1, 2, 1], [0, 1, 5]], src = 0
ExampleOutput: [0, 5, 6, 6, 7]
Input: V = 4, edges = [[0, 1, 4], [1, 2, -6], [2, 3, 5], [3, 1, -2]], src = 0
ExampleOutput: [-1]
Explanation: The graph contains negative weight cycle.
Approach
The Bellman-Ford algorithm works by traversing all edges |V| - 1
times, where |V|
is the number of vertices. After each iteration, the algorithm relaxes all the edges. If a shorter path is found from the source to a vertex during any iteration, then the distance of that vertex is updated.
Step-by-step algorithm
- Initialize distances to all vertices as infinite and the distance to the source vertex as 0.
- Relax all edges
|V| - 1
times. - If we can find a shorter path, then there is a negative weight cycle in the graph.
Working of Bellman-Ford Algorithm
Below is the Python implementation of the algorithm:
Python
def bellman_ford(graph, source):
# Step 1: Initialize distances
distances = {vertex: float('inf') for vertex in graph}
distances[source] = 0
# Step 2: Relax edges |V| - 1 times
for _ in range(len(graph) - 1):
for u in graph:
for v, weight in graph[u].items():
if distances[u] != float('inf') and distances[u] + weight < distances[v]:
distances[v] = distances[u] + weight
# Step 3: Check for negative weight cycles
for u in graph:
for v, weight in graph[u].items():
if distances[u] != float('inf') and distances[u] + weight < distances[v]:
raise ValueError("Graph contains negative weight cycle")
return distances
# Example
graph = {
'A': {'B': -1, 'C': 4},
'B': {'C': 3, 'D': 2, 'E': 2},
'C': {},
'D': {'B': 1, 'C': 5},
'E': {'D': -3}
}
source = 'A'
shortest_distances = bellman_ford(graph, source)
print(shortest_distances)
Output{'A': 0, 'B': -1, 'C': 2, 'D': -2, 'E': 1}
Time Complexity: O(V * E * E), where V is the number of vertices and E is the number of edges
Auxiliary Space: O(V)
Similar Reads
Interview Preparation
Practice @Geeksforgeeks
Data Structures
Algorithms
Programming Languages
Web Technologies
Computer Science Subjects
Data Science & ML
Tutorial Library
GATE CS