Skip to main content

Bellman-Ford Algorithm

Bellman-Ford solves the single-source shortest paths problem on a weighted directed graph that may contain negative edges. Unlike Dijkstra, it does not assume any sign restriction on the weights; in exchange, it runs in O(VE)O(V E) instead of O((V+E)log⁡V)O((V + E) \log V). It also doubles as the standard certificate for the existence of a negative-weight cycle reachable from the source — if one exists, there is no well-defined shortest path, and the algorithm reports failure.

The idea is disarmingly simple: relax every edge V−1V - 1 times. Because any shortest path has at most V−1V - 1 edges (otherwise it would contain a repeated vertex, i.e. a cycle, which could be excised without increasing the weight), V−1V - 1 full passes are sufficient to propagate any finite shortest distance. A VV-th pass that still improves some distance witnesses a negative cycle.

The solve function takes [n, edges, source] with edges as [u, v, w] triples on vertices 0,1,…,n−10, 1, \dots, n - 1, and returns the distance array with 10**18 for unreachable vertices. If a negative cycle is reachable from source, it returns [].

Codes​

def solve(xs):
"""xs = [n, edges, source]. Return distances (10**18 for unreachable),
or [] if a negative cycle is reachable from source."""
n, edges, source = xs
INF = 10**18
dist = [INF] * n
dist[source] = 0
for _ in range(n - 1):
updated = False
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
updated = True
if not updated:
break
# One more pass: if anything still improves, there is a negative cycle
# reachable from source.
for u, v, w in edges:
if dist[u] != INF and dist[u] + w < dist[v]:
return []
return dist

Example​

Loading Python runner...

Description​

Run time analysis​

O(VE)O(V E). Each of the V−1V - 1 passes relaxes all EE edges. The final negative-cycle check is another O(E)O(E). The early-exit when a pass does no updates often makes the algorithm much faster on easy inputs but does not improve the worst case.

Space analysis​

O(V+E)O(V + E). The distance array is O(V)O(V) and the edge list is read as input, so no adjacency structure is required.

Proof of correctness​

Let δ(s,v)\delta(s, v) denote the length of the shortest ss-to-vv walk in the graph (taking the value −∞-\infty if the graph has a negative cycle reachable from ss on every ss-to-vv path).

Claim. If the graph has no negative cycle reachable from ss, then after the kk-th relaxation pass dist[v]≤dist[v] \le the minimum weight of any ss-to-vv walk that uses at most kk edges.

Induction on kk. Base k=0k = 0: dist[s]=0dist[s] = 0 and dist[v]=∞dist[v] = \infty for v≠sv \ne s, and the only walk with zero edges is the empty walk at ss itself.

Inductive step. Suppose the claim holds for k−1k - 1, and consider a shortest ss-to-vv walk PP using at most kk edges. If PP uses fewer than kk edges, the inductive hypothesis already gives dist[v]≤w(P)dist[v] \le w(P). Otherwise let uu be the predecessor of vv on PP, so the prefix of PP is an ss-to-uu walk of at most k−1k - 1 edges with weight w(P)−w(u,v)w(P) - w(u, v). By induction, dist[u]≤w(P)−w(u,v)dist[u] \le w(P) - w(u, v) just before the kk-th pass. During the kk-th pass the algorithm relaxes (u,v)(u, v) and sets dist[v]≤dist[u]+w(u,v)≤w(P)dist[v] \le dist[u] + w(u, v) \le w(P), so the claim holds after pass kk.

Because any simple shortest path has at most V−1V - 1 edges, and in the absence of a negative cycle we never improve by adding cycles, after V−1V - 1 passes dist[v]=δ(s,v)dist[v] = \delta(s, v) for every vertex reachable from ss. Unreachable vertices stay at ∞\infty (here encoded as 101810^{18}).

Negative-cycle detection. If a negative cycle is reachable from ss, then for some edge (u,v)(u, v) on that cycle we have δ(s,u)+w(u,v)<δ(s,v)\delta(s, u) + w(u, v) < \delta(s, v) — the cycle can be traversed once more to strictly decrease the tentative distance of vv. So the VV-th pass will still relax some edge. Conversely, if the VV-th pass relaxes some edge, then there is a walk of more than V−1V - 1 edges improving on any (V−1)(V - 1)-edge walk, which forces a cycle of negative total weight.

Extensions​

Applications​

References​

  • Cormen, Leiserson, Rivest, Stein. Introduction to Algorithms, 3rd ed., Chapter 24 (Single-Source Shortest Paths).
  • Bellman, R. (1958). "On a routing problem." Quarterly of Applied Mathematics, 16(1), 87-90.
  • cp-algorithms — Bellman-Ford