← Lessons

quiz vs the machine

Gold1370

Algorithms

Bellman Ford Negative Cycle

Relax every edge repeatedly to find shortest paths even with negative weights, and detect cycles that lower cost without bound.

6 min read · core · beat Gold to climb

Relax every edge

Bellman Ford finds shortest paths from a single source and tolerates negative edge weights. It relaxes every edge in the graph, then repeats that full sweep. After a number of sweeps equal to one less than the node count, all shortest paths are settled, because any simple path uses at most that many edges.

Detecting negative cycles

After the final sweep, run one extra pass over all edges. If any edge can still be relaxed to a smaller distance, the graph contains a negative cycle reachable from the source. Such a cycle means there is no well defined shortest path, since looping reduces cost without limit.

  • Sweep all edges, relaxing distances.
  • Repeat until paths stabilize.
  • One more sweep that still improves signals a negative cycle.

Key idea

Bellman Ford relaxes every edge across repeated sweeps to handle negative weights, and a final sweep that still improves a distance proves the existence of a reachable negative cycle.

Check yourself

Answer to earn rating on the learn ladder.

1. How many full sweeps are enough to settle all distances without a negative cycle?

2. What does an extra sweep that still relaxes an edge indicate?