Skip to content
BytePatterns

Bellman-Ford

Graphs: lesson 9 of 16

Relax every edge, V-1 times, and negative weights stop being a problem.

Lesson 9 of 16 · 6 min

Bellman-Ford

Step 1 of 8

No heap, no ordering. Every node starts at ∞ and the whole edge list will be swept, V-1 = 3 times.

The Idea

Dijkstra settles the nearest node and never looks back, which a negative edge can invalidate. Bellman-Ford refuses to settle anything. It just relaxes every edge, round after round, V-1 times — enough for the longest possible shortest path. One extra round that still improves something proves the graph has a negative cycle.

Real-World Example

A freight desk pricing routes where some legs carry a rebate, so a leg can cost less than nothing. Nearest-first pricing would lock in a quote before the rebate leg is seen. Sweeping every leg repeatedly keeps every quote provisional until the numbers stop moving.

The Code

edges = [("a", "b", 4), ("a", "c", 5), ("b", "c", -3), ("c", "d", 3)]
nodes = ["a", "b", "c", "d"]
dist = {n: float("inf") for n in nodes}
dist["a"] = 0

for _ in range(len(nodes) - 1):        # V-1 rounds is always enough
    for u, v, w in edges:
        if dist[u] + w < dist[v]:      # relax every edge, every round
            dist[v] = dist[u] + w

negative_cycle = any(dist[u] + w < dist[v] for u, v, w in edges)
print(dist)             # {'a': 0, 'b': 4, 'c': 1, 'd': 4}
print(negative_cycle)   # False

Python

Your turn

What does this print?

dist = {"a": 0, "b": 7, "c": float("inf")}
for u, v, w in [("a", "b", 2), ("b", "c", -5)]:
  if dist[u] + w < dist[v]:
      dist[v] = dist[u] + w
print(dist["b"], dist["c"])

Mini quiz

1 / 3

Why does Bellman-Ford survive negative edges when Dijkstra does not?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.