Bellman-Ford for Negative Weights

The Bellman-Ford algorithm computes single-source shortest paths in directed graphs that may contain negative edge weights by relaxing every edge for V-1 passes. A V-th pass detects negative cycles reachable from the source.

Step 1 of 157%

Tutorial

Why Bellman-Ford? The Edge Relaxation Step

The Bellman-Ford algorithm computes single-source shortest paths in a directed graph that may contain negative edge weights.

Dijkstra's algorithm fails on negative edges because its greedy strategy permanently finalizes the closest unvisited vertex. Once a vertex is finalized, a later negative edge that would shorten its distance is never considered. Bellman-Ford avoids this by never committing: it repeatedly improves a running estimate d[v]d[v] of the shortest-path distance from the source ss to each vertex vv.

Initialize

d[s]=0,d[v]= for all vs.d[s] = 0, \qquad d[v] = \infty \text{ for all } v \ne s.

The edge relaxation of a directed edge (u,v)(u, v) with weight w(u,v)w(u, v) is the test

if d[u]+w(u,v)<d[v], then d[v]d[u]+w(u,v).\text{if } d[u] + w(u, v) < d[v], \text{ then } d[v] \leftarrow d[u] + w(u, v).

For example, suppose at some point d[u]=3d[u] = 3, d[v]=10d[v] = 10, and w(u,v)=5w(u, v) = -5. We compute the candidate distance

d[u]+w(u,v)=3+(5)=2.d[u] + w(u, v) = 3 + (-5) = -2.

Since 2<10-2 < 10, the test succeeds and we update d[v]2d[v] \leftarrow -2. If d[v]d[v] had instead been 7-7, the candidate 2-2 would not beat 7-7 and we would leave d[v]d[v] unchanged.

navigate · Enter open · Esc close · ⌘K/Ctrl K toggle