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
Bellman Ford Algorithm in C++ The Bellman-Ford algorithm is a single-source shortest path algorithm that finds the shortest path from a given source vertex to all other vertices in a graph. Unlike Dijkstraâs algorithm, Bellman-Ford can handle graphs with negative edge weights, making it useful in various scenarios. In this artic
5 min read
Bellman-Ford Algorithm in C The Bellman-Ford algorithm helps find the shortest path from one starting point to all other points in a graph, even if some paths have negative weights. It's useful for network routing problems. In this article, we will learn about the Bellman-Ford algorithm and how to implement it in C. The Bellma
4 min read
BellmanâFord Algorithm Given a weighted graph with V vertices and E edges, along with a source vertex src, the task is to compute the shortest distances from the source to all other vertices. If a vertex is unreachable from the source, its distance should be marked as 108. In the presence of a negative weight cycle, retur
10 min read
Bitwise Algorithm in Python Bitwise algorithms refer to the use of bitwise operators to manipulate individual bits of data. Python provides a set of bitwise operators such as AND (&), OR (|), XOR (^), NOT (~), shift left (<<), and shift right (>>). These operators are commonly used in tasks like encryption, com
6 min read
Bellman Ford Algorithm (Simple Implementation) We have introduced Bellman Ford and discussed on implementation here.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 di
13 min read
Ford-Fulkerson Algorithm in Python The Ford-Fulkerson algorithm is a widely used algorithm to solve the maximum flow problem in a flow network. The maximum flow problem involves determining the maximum amount of flow that can be sent from a source vertex to a sink vertex in a directed weighted graph, subject to capacity constraints o
4 min read