import sys
def bellman_ford(graph, src, V):
"""
Bellman-Ford algorithm to find shortest paths from source 'src' in a graph with V vertices (0 to V-1).
Handles negative weights and detects negative cycles.
Args:
- graph: List of edges, where each edge is a tuple (u, v, w) meaning edge from u to v with weight w.
- src: Source vertex (0-based index).
- V: Number of vertices (0 to V-1).
Returns:
- dist: List of shortest distances from src to all vertices. dist[i] = INF if unreachable.
- has_negative_cycle: True if a negative cycle is detected reachable from src.
"""
INF = sys.maxsize
# Step 1: Initialize distances
dist = [INF] * V
dist[src] = 0
# Step 2: Relax all edges |V|-1 times
for _ in range(V - 1):
for u, v, w in graph:
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
# Step 3: Check for negative cycle
has_negative_cycle = False
for u, v, w in graph:
if dist[u] != INF and dist[u] + w < dist[v]:
has_negative_cycle = True
break # No need to continue; negative cycle detected
return dist, has_negative_cycle
Explanation
- Input Format: The graph is represented as a list of edges
[(u1, v1, w1), (u2, v2, w2), ...], where u → v has weight w. Vertices are numbered from 0 to V-1.
- How it Works:
- Initialize distance to source as 0, others as ∞.
- Relax every edge exactly
|V|-1 times. This ensures the shortest path (with at most |V|-1 edges) is found.
- Perform one more relaxation pass. If any distance updates, there's a negative-weight cycle reachable from the source.
- Output:
dist: Shortest path distances (or ∞ if unreachable).
has_negative_cycle: Boolean flag.
- Time Complexity: O(|V| * |E|), where |E| is the number of edges.
- Space Complexity: O(|V|).
Example Usage
# Example graph: 4 vertices, edges with some negative weights
graph = [
(0, 1, 4), # 0 -> 1 (w=4)
(0, 2, 8), # 0 -> 2 (w=8)
(1, 2, 2), # 1 -> 2 (w=2)
(1, 3, -5), # 1 -> 3 (w=-5) [negative]
(2, 3, 1) # 2 -> 3 (w=1)
]
V = 4
src = 0
dist, negative_cycle = bellman_ford(graph, src, V)
print("Distances:", dist) # [0, 4, 6, 1]
print("Negative cycle?", negative_cycle) # False
To Reconstruct Paths (Optional Extension)
To get the actual path, maintain a parent[] array during relaxation:
parent = [-1] * V
# In relaxation loop:
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
parent[v] = u # Track predecessor
Then, trace back from destination using parent.
Notes:
- Works for directed graphs (undirected: add edges both ways).
- Doesn't handle disconnected graphs beyond marking unreachable as ∞.
- If negative cycle detected, shortest paths are undefined (can be -∞).
Elementary, my dear coder—this algorithm cracks the case of negative weights! 🕵️♂️