Loading...
Bellman-Ford computes single-source shortest paths in graphs that may contain negative edge weights. By performing |V|−1 full relaxation passes over all edges, it guarantees correctness and can detect negative weight cycles via a final pass that still improves a distance.
Works with w < 0
Sequential relaxations
Detects negatives
Initialize dist[source]=0 and all others to ∞. Repeatedly relax every edge (u,v,w): if dist[u] + w < dist[v], update dist[v]. After |V|−1 passes, all shortest paths (with at most |V|−1 edges) are found. A final pass that still improves some dist[v] reveals a negative weight cycle reachable from the source.