Data Structures · Visualization
Bellman-Ford
Graph
Bellman-Ford also finds the shortest path from a source to all other nodes, but unlike Dijkstra, it correctly handles graphs with negative edge weights, and can even detect if a 'negative cycle' exists (a loop that reduces total cost indefinitely, which would make 'shortest path' meaningless). Time: O(V * E). Space: O(V) for distances.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Bellman-Ford
GraphBellman-Ford also finds the shortest path from a source to all other nodes, but unlike Dijkstra, it correctly handles graphs with negative edge weights, and can even detect if a 'negative cycle' exists (a loop that reduces total cost indefinitely, which would make 'shortest path' meaningless). It works by relaxing every single edge in the graph, repeated for V-1 rounds, guaranteeing that the shortest path — however many edges it uses — has been found.
How Bellman-Ford Works
- Set the source node's distance to 0 and every other node's distance to infinity.
- Repeat V-1 times (where V is the number of nodes): for every edge in the graph, check if going through it offers a shorter path to its destination, and update the distance if so.
- After V-1 rounds, all shortest paths (assuming no negative cycles) are finalized.
- Run one more round: if any distance can still be improved, a negative cycle exists.
Bellman-Ford Worked Example
Input: Graph with edges A-B(4), A-C(5), B-C(-2), source = A, 3 nodes
- distance: A=0, B=infinity, C=infinity
- Round 1: relax A-B → B=4; relax A-C → C=5; relax B-C → C = 4 + (-2) = 2, better, update C=2
- Round 2 (V-1=2 total): no further improvements found
- Extra check round: no improvements → no negative cycle
Output: Shortest distances from A: B=4, C=2
Press ▶ Run to watch it step by step.
def bellman_ford(n, edges, start):
dist = [float('inf')] * n
dist[start] = 0
for _ in range(n - 1):
for a, b, w in edges:
if dist[a] + w < dist[b]:
dist[b] = dist[a] + w
# one more pass to detect negative cycles
for a, b, w in edges:
if dist[a] + w < dist[b]:
return None # negative cycle
return dist
# example: Bellman-Ford fromBehind 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 (where negative cycles represent profitable loops)
- Network routing protocols that must handle penalty/negative-adjustment weights
- Any shortest-path problem where negative edge weights are possible
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.