← Knowledgebase

Bellman–Ford: shortest paths with negative edges

When Dijkstra breaks

Dijkstra's algorithm settles the closest node and never revisits it. That's only safe when edges can't be negative: otherwise a longer detour can end with a negative edge and come out shorter. Negative lengths are natural when edges are costs and gains, such as fees and rebates, energy used and recovered, or exchange rates taken as logarithms.

The idea: relax every edge, repeatedly

Bellman–Ford doesn't try to be clever about order. Every node gets a distance (0 for the start, ∞ otherwise). Then, in each pass, it checks every edge u→v once: if going through u is shorter than v's current distance, lower it. That check is called relaxing the edge.

  1. After pass 1, every node whose shortest path has 1 edge has its final distance. After pass 2, those with 2 edges, and so on.
  2. A shortest path never repeats a node, so it has at most V − 1 edges: V − 1 passes are always enough.
  3. If a pass changes nothing, no later pass can, so you can stop early.

Negative cycles

If some cycle has negative total length, going round it again and again makes paths as short as you like: there is no shortest path. Bellman–Ford detects this with one extra pass. After V − 1 passes everything should be final, so if pass V still lowers a distance, a negative cycle must be to blame. Following the best-path edges backwards from that node leads into the cycle.

Reading the pictures

A distance ∞ B has a distance C start of the edge being checked

Numbers under the nodes are their current distances; blue edges are the best paths found so far. Each pass checks the edges in alphabetical order (A→B, A→E, B→C, …), and a distance only changes when the new path is strictly shorter. An edge can only lower anything if its start node's distance has changed since the edge was last checked; the others are passed over in one step.

DijkstraBellman–Ford
TimeO((V + E) log V)O(V · E)
Negative edgesWrong answersFine
Negative cyclesNot detectedDetected

The order of the edges doesn't change the answer, only how many passes it takes. In the example, the edges happen to come in a helpful order; in the worst case it takes all V − 1 passes.