AlgoFrames

Bellman-Ford and negative edges

Bellman-Ford relaxes every edge n − 1 times, so it handles negative weights. One more round that still improves a distance reveals a negative cycle.

Before you start: Dijkstra's algorithm.

The idea

A courier route has one leg that pays a rebate of 3. The cheapest route must count that negative cost.

Negative weights show up as rebates, refunds and exchange-rate gains. Dijkstra cannot handle them.

Intuition

Dijkstra settles node 1 at 4 before it reaches node 2. The route 0 → 2 → 1 costs 5 − 3 = 2, so the greedy rule fails.

A shortest path visits each node once, so it has at most n − 1 edges. Each round of relaxing every edge fixes one more edge of it.

After round r, every node whose shortest path has r edges or fewer holds its final distance. This holds for any edge order.

Complexity

Each round checks all E edges, and at most V − 1 rounds run. The total is O(V · E).

With non-negative weights, Dijkstra needs only O((V + E) log V). Pay for Bellman-Ford only when negative edges appear.

The only extra memory is one distance per node, so space is O(V).

Pitfalls

The loop 1 → 2 → 3 → 1 costs −1 per lap, so every lap lowers the distances again. The ✕ nodes have no shortest distance.

After n − 1 rounds all real shortest paths are final. An extra pass that still improves an edge proves a negative cycle.

An undirected edge of weight −2 is a negative cycle by itself. Walking 0 → 1 → 0 costs −4, so neither node has a distance.

Variations

Cheapest flights with at most k stops runs only k + 1 rounds. The graph shows k = 1; with k = 2 the price to 3 drops to 400.

Reading last round's copy stops a route from growing by two flights in one round.

Code

Pseudocode

dist[all] ← ∞, dist[source] ← 0
repeat n − 1 times
  changed ← false
  for each edge (u, v, w)
    if dist[u] + w < dist[v]
      dist[v] ← dist[u] + w
      changed ← true
  if not changed: stop early
for each edge (u, v, w)
  if dist[u] + w < dist[v]: report negative cycle
return dist

Python

def bellman_ford(n, edges, source):
    dist = [float("inf")] * n
    dist[source] = 0
    for _ in range(n - 1):
        changed = False
        for u, v, w in edges:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                changed = True
        if not changed:
            break
    for u, v, w in edges:
        if dist[u] + w < dist[v]:
            return None
    return dist

JavaScript

function bellmanFord(n, edges, source) {
  const dist = new Array(n).fill(Infinity);
  dist[source] = 0;
  for (let round = 1; round < n; round++) {
    let changed = false;
    for (const [u, v, w] of edges) {
      if (dist[u] + w < dist[v]) {
        dist[v] = dist[u] + w;
        changed = true;
      }
    }
    if (!changed) break;
  }
  for (const [u, v, w] of edges) {
    if (dist[u] + w < dist[v]) return null;
  }
  return dist;
}

Java

int[] bellmanFord(int n, int[][] edges, int source) {
    final int INF = Integer.MAX_VALUE;
    int[] dist = new int[n];
    Arrays.fill(dist, INF);
    dist[source] = 0;
    for (int round = 1; round < n; round++) {
        boolean changed = false;
        for (int[] e : edges) {
            if (dist[e[0]] != INF && dist[e[0]] + e[2] < dist[e[1]]) {
                dist[e[1]] = dist[e[0]] + e[2];
                changed = true;
            }
        }
        if (!changed) break;
    }
    for (int[] e : edges) {
        if (dist[e[0]] != INF && dist[e[0]] + e[2] < dist[e[1]]) return null;
    }
    return dist;
}

Cost at a glance

TimeO(V · E)
SpaceO(V)
InputAny weights
OutputShortest distances or a negative cycle

Practice problems (4)

Rounds needed Warm-up

Bellman-Ford runs from node 0 on a chain of 4 nodes. The edges are listed from the far end first. Answer each question before the step plays.

Implement Bellman-Ford Standard

A directed graph has n nodes and edges, where edges[i] = [from, to, weight]. Weights may be negative, but no negative cycle exists. Return dist, where dist[v] is the shortest distance from source to v.

Use -1 for an unreachable node. Tests never have a reachable node whose shortest distance is -1.

Cheapest flights within k stops Standard

There are n cities and one-way flights, where flights[i] = [from, to, price]. Return the cheapest price from src to dst using at most k stops, or -1 when no such route exists.

A route with k stops uses k + 1 flights.

Detect a negative cycle Standard

A directed graph has n nodes and weighted edges, where edges[i] = [from, to, weight]. Return true when the graph contains a cycle whose weights add up to less than 0, anywhere in the graph.

Related topics

Next on the path: 0-1 BFS and multi-source BFS