27. Bellman-Ford Algorithm
Description
The Bellman-Ford Algorithm is an algorithm for finding the shortest paths from a single source vertex to all other vertices in a weighted graph. Unlike Dijkstra's algorithm, which only works on graphs with non-negative edge weights, the Bellman-Ford algorithm can handle graphs containing negative edge weights. However, it cannot correctly produce shortest paths if the graph contains a negative-weight cycle (a cycle whose total edge weight sum is negative).
The algorithm works by iteratively relaxing all edges in the graph. It sequentially improves shortest-path estimates by checking all edges and updating vertex distances.
Steps of the Bellman-Ford Algorithm:
- Initialize distances: Set the distance to all vertices to infinity (∞), except for the starting vertex, which is set to 0.
- Edge Relaxation: For every edge (u, v) with weight w(u, v), check if the distance to vertex v can be shortened by going through vertex u:
dist[v] = min(dist[v], dist[u] + w(u, v))
- Repeat Relaxation: Repeat step 2 for all edges V - 1 times (where V is the number of vertices). This guarantees finding shortest paths for graphs without negative cycles.
- Negative Cycle Detection: After V - 1 iterations, run one more check across all edges. If any distance can still be reduced, it indicates the presence of a negative-weight cycle.
Example Output
Shortest distances from vertex 0:
- To vertex 0: 0
- To vertex 1: -1
- To vertex 2: 2
- To vertex 3: -2
- To vertex 4: 1
Step-by-Step Explanation
- Initialization:
Set the distance from the starting vertex to itself as 0 and to all other vertices as infinity (∞).
- Edge Relaxation:
In each pass, iterate through every edge in the graph. If going through vertex u to vertex v yields a shorter path than currently known, update dist[v].
- Negative Cycle Verification:
After completing V - 1 iterations, check all edges once more. If a path distance can still be decreased, a negative cycle exists, and the algorithm reports it.
Python Implementation
INF = float('inf')
def bellman_ford(graph, start):
"""
Implementation of the Bellman-Ford algorithm to find shortest paths
from a start vertex to all other vertices in a graph.
graph - list of edges represented as tuples (u, v, weight)
start - starting vertex identifier
Returns a dictionary of shortest distances from start to all vertices.
"""
# Initialize distances
dist = {i: INF for i in range(len(graph))}
dist[start] = 0
# Relax edges V - 1 times (where V is the number of vertices)
for _ in range(len(graph) - 1):
for u, v, weight in graph:
if dist[u] != INF and dist[u] + weight < dist[v]:
dist[v] = dist[u] + weight
# Check for negative-weight cycles
for u, v, weight in graph:
if dist[u] != INF and dist[u] + weight < dist[v]:
print("Graph contains a negative-weight cycle!")
return None
return dist
# Example usage:
# Graph represented as an edge list: (u, v, edge_weight)
graph = [
(0, 1, -1), # Edge from vertex 0 to vertex 1 with weight -1
(0, 2, 4), # Edge from vertex 0 to vertex 2 with weight 4
(1, 2, 3), # Edge from vertex 1 to vertex 2 with weight 3
(1, 3, 2), # Edge from vertex 1 to vertex 3 with weight 2
(1, 4, 2), # Edge from vertex 1 to vertex 4 with weight 2
(3, 2, 5), # Edge from vertex 3 to vertex 2 with weight 5
(3, 1, 1), # Edge from vertex 3 to vertex 1 with weight 1
(4, 3, -3) # Edge from vertex 4 to vertex 3 with weight -3
]
start = 0
distances = bellman_ford(graph, start)
if distances:
print(f"Shortest distances from vertex {start}:")
for vertex, distance in distances.items():
print(f"To vertex {vertex}: {distance}")
Complexity
- Time Complexity: O(V · E), where V is the number of vertices and E is the number of edges. The algorithm performs V - 1 iterations, checking all E edges in each step.
- Space Complexity: O(V), as it requires storing shortest distance values for all vertices in the graph.
Applications of the Bellman-Ford Algorithm
- Graphs with Negative Edge Weights: Unlike Dijkstra's algorithm, Bellman-Ford reliably handles graphs that contain edges with negative weights.
- Negative Cycle Detection: Used to detect negative cycles in graphs, which is crucial for analyzing financial systems, trade loops, and network models.
- Financial Modeling: Applied in foreign exchange arbitrage detection, where negative cycles correspond to profitable currency exchange loops.
- Graph Theory: Frequently used in theoretical computational graph problems and routing protocols (such as Distance-Vector Routing protocols like RIP).
Conclusion
The Bellman-Ford algorithm is a versatile tool for finding single-source shortest paths in graphs with arbitrary edge weights and serves as an effective mechanism for detecting negative-weight cycles.
All rights remain with the original author (Archiveskk). Publishing here does not grant a license to copy or reuse this text. Copyright & license. If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me