Menu
Coddy logo textTech

Bellman-Ford Algorithm

Last updated

Bellman-Ford finds the shortest path from a source node to every other node, and unlike Dijkstra it works even when some edge weights are negative. It works by brute-force relaxation: it repeatedly scans every edge and, if going through that edge gives a shorter distance, it updates the target's distance. Press play above to watch the tentative distances drop pass by pass.

After V - 1 passes over all edges, every shortest path (which can have at most V - 1 edges) has been found. This makes it O(V · E) - slower than Dijkstra, but it handles negative weights and can detect a negative-weight cycle (if a V-th pass still relaxes an edge, no shortest path exists).

Time & space complexity

MeasureComplexityNotes
TimeO(V · E)V − 1 passes over all E edges
SpaceO(V)One distance per node
Negative weightsSupportedIts key advantage over Dijkstra
Negative cyclesDetectableA relaxing V-th pass signals one

Step by step

StepWhat happens
1Set the source distance to 0 and all others to infinity.
2Repeat the next step V − 1 times.
3For every edge (u → v, w), check if dist[u] + w < dist[v].
4If so, relax it: set dist[v] = dist[u] + w.
5Stop early if a full pass makes no change.

Worked example

Source S on 4 nodes S, A, B, C with edges S→A (4), S→B (5), A→C (3), B→A (-3), relaxed in that order. Distances start at S=0 and everything else :

PassDistances [S, A, B, C]Action
Init[0, ∞, ∞, ∞]Source distance is 0, all others infinity.
1[0, 2, 5, 7]Relax S→A to 4, S→B to 5, A→C to 7, then B→A lowers A to 5 + (-3) = 2.
2[0, 2, 5, 5]A→C now improves C to 2 + 3 = 5; no other edge relaxes.
3[0, 2, 5, 5]No edge relaxes, so distances are final: A costs 2 via S→B→A.

When to use Bellman-Ford

Use it whenAvoid it when
Edge weights can be negative.All weights are non-negative (Dijkstra is faster).
You must detect negative-weight cycles.The graph is huge and dense - O(V · E) is too slow.
The graph is small or sparse.You only need a single source-to-target query on a big graph.
You need a simple, easy-to-implement baseline.Weights are non-negative and latency matters.

Bellman-Ford Algorithm code

A clean, runnable Bellman-Ford Algorithm implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Bellman-Ford Algorithm code in Python

Python
1def bellman_ford(vertices, edges, start):2    dist = {v: float("inf") for v in vertices}3    dist[start] = 04    # Relax every edge V-1 times5    for _ in range(len(vertices) - 1):6        for u, v, w in edges:7            if dist[u] + w < dist[v]:8                dist[v] = dist[u] + w9    # One more pass: any improvement means a negative cycle10    for u, v, w in edges:11        if dist[u] + w < dist[v]:12            raise ValueError("Graph contains a negative-weight cycle")13    return dist14
15
16vertices = ["A", "B", "C", "D", "E"]17edges = [18    ("A", "B", 6), ("A", "C", 7), ("B", "D", 5), ("B", "E", -4),19    ("C", "D", -3), ("D", "B", -2), ("E", "D", 7),20]21
22for node, d in bellman_ford(vertices, edges, "A").items():23    print(f"A -> {node}: {d}")
Run this code in the Python Playground

Bellman-Ford FAQ

What is the time complexity of Bellman-Ford?
Bellman-Ford runs in O(V · E) time: it makes V - 1 passes, and each pass relaxes all E edges. That is slower than Dijkstra's O((V + E) log V), which is the price of supporting negative edge weights.
When should I use Bellman-Ford instead of Dijkstra?
Use Bellman-Ford when the graph can have negative edge weights, or when you need to detect negative-weight cycles. Dijkstra is faster but only correct with non-negative weights. A common real use is currency-exchange arbitrage detection, where negative cycles matter.
How does Bellman-Ford detect a negative cycle?
After the V - 1 relaxation passes, all shortest paths are finalized if no negative cycle exists. If one more pass can still relax an edge, then a negative-weight cycle is reachable, and shortest paths are undefined (you could loop forever to lower the cost).
What is the difference between Bellman-Ford and Floyd-Warshall?
Bellman-Ford computes shortest paths from a single source in O(V · E), while Floyd-Warshall computes all-pairs shortest paths in O(V³). On a dense graph, running Bellman-Ford from every source costs O(V² · E), so Floyd-Warshall is usually the better choice when you need every pair. Both handle negative edges and can flag negative cycles.
Why does Bellman-Ford need exactly V - 1 passes?
Any shortest path in a graph with no negative cycle uses at most V - 1 edges, because a path visiting more than V nodes must repeat one. Each pass guarantees at least one more edge of every shortest path is relaxed correctly, so V - 1 passes are enough to settle them all. A common misconception is that more passes improve the answer - they never do unless a negative cycle exists.
Can Bellman-Ford stop early?
Yes. If a full pass over all edges relaxes nothing, every distance is already optimal and you can stop before reaching V - 1 passes. This early-exit optimization often makes it much faster on graphs that converge quickly, though the worst-case bound stays O(V · E).
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED