224. How does Bellman-Ford work, and how does it detect negative cycles?
MediumGraph algorithms
Technical
Show model answer
Initialize dist[source] = 0 and everything else to infinity, then relax every edge V − 1 times. A shortest simple path has at most V − 1 edges, so after V − 1 rounds all shortest distances are final if there is no negative cycle reachable from the source. Stop early if a round changes nothing.
Run one more round: if any edge can still be relaxed, a negative cycle is reachable and shortest paths are undefined. Time O(V·E), space O(V). It is slower than Dijkstra but handles negative weights and is the core of distance-vector routing and Johnson's reweighting.