Algorithms · Visualized
Bellman–Ford
Graph Algorithms
Traverse, order, and find shortest paths and spanning trees on graphs — the machinery behind maps, networks, schedulers and dependency resolvers.
Bellman–Ford tolerates negative edge weights where Dijkstra breaks. Time: O(V·E) average, O(V·E) worst; space: O(V) for the distance array.
Big-O: Traversals O(V + E); Dijkstra O(E log V) with a heap; Bellman–Ford O(V·E); Floyd–Warshall O(V³); MST O(E log E).
Bellman–Ford
Graph AlgorithmsBellman–Ford tolerates negative edge weights where Dijkstra breaks. It simply relaxes every edge, round after round — after V−1 rounds every shortest path (which uses at most V−1 edges) is guaranteed to be final. A Vth round that still improves a distance therefore proves a negative cycle reachable from the source.
How Bellman–Ford Works
- Set dist[start] = 0 and everything else to ∞.
- Repeat V−1 rounds; in each round relax every edge (u, v, w): if dist[u] + w < dist[v], update dist[v].
- Correct distances propagate at least one extra hop per round, so V−1 rounds always suffice.
- Round V: if any edge can still be relaxed, a negative cycle is reachable from the source — report it.
- Early-exit when a round changes nothing; the distances are already final.
Bellman–Ford Worked Example
Input: {graph: A—B(4), A—C(2), B—C(1), B—D(5), C—D(8), C—E(10), D—E(2), D—F(6), E—F(3), start: A}
Round 1 relaxes edges in order, pushing 0 outwards: B=4, C=2, then C→B improves B to 3, C→D=10, D→E=12, D→F=10. Round 2: B→D improves D to 8, D→E improves to 10, D→F to 14… after V−1 rounds: B=3 C=2 D=8 E=10 F=13. Round V changes nothing → no negative cycle.
def bellman_ford(n, edges, start):
dist = [float('inf')] * n
dist[start] = 0
for _ in range(n - 1): # relax every edge n-1 times
changed = False
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
changed = True
if not changed:
break
# one more pass detects negative cycles
for u, v, w in edges:
if dist[u] + w < dist[v]:
raise ValueError('negative cycle')
return distBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Bellman–Ford Time & Space Complexity
When to Use Bellman–Ford
- Currency arbitrage detection: a profitable cycle is exactly a negative cycle in exchange-rate graphs.
- Distance-vector routing protocols (RIP) and any graph that must allow negative weights.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.