Bellman–Ford visualization

Relax every edge V−1 times; handles negative weights and detects negative cycles.

A shortest path has at most V−1 edges, so V−1 rounds of relaxing every edge are enough to find all distances — even with negative weights.

If a V-th round can still shorten something, a negative cycle is reachable and "shortest path" is undefined (you could loop forever, getting cheaper).

Complexity

Time: best O(E), average O(V·E), worst O(V·E). Space: O(V). Difficulty: Intermediate.

Pseudocode

procedure bellmanFord(G, s):
  dist[*] ← ∞; dist[s] ← 0
  repeat |V| − 1 times:
    for each edge (u, v, w):
      if dist[u] + w < dist[v]: dist[v] ← dist[u] + w
    if nothing changed: stop early
  for each edge (u, v, w):
    if dist[u] + w < dist[v]: negative cycle!
  return dist

More graphs algorithms