Home
DSA Visualizer
Data Structures
Bellman-Ford Algorithm
Bellman-Ford Algorithm
The Bellman-Ford algorithm finds the shortest paths from a source in a graph that may contain negative-weight edges, and detects negative-weight cycles.
INIT
Distances before the first pass
Edge list (walked in order)
Every distance starts at ∞ except A, which is 0.
Next
Pass 1 of 3: walk the whole edge list and relax whatever will relax.
Intuition
Unlike Dijkstra, which aggressively chooses the shortest known path, Bellman-Ford is cautious.
It assumes any path could be improved by any edge, so it iteratively checks all edges to see if they can offer a shortcut.
This careful approach allows it to handle negative edge weights.
Concept
- Relaxation: Checking if an edge (u, v) with weight w allows us to reach v cheaper than before (dist[v] > dist[u] + w).
- V-1 Iterations: In a graph with V nodes, the longest simple path can have at most V-1 edges. Repeating relaxation V-1 times guarantees finding shortest simple paths.
- Negative Cycle: If we can still relax an edge after V-1 iterations, it means there's a cycle that reduces total distance forever (Negative Cycle).
How it Works
- Initialize distances:
dist[start] = 0, others = ∞. - Repeat
V-1times:- Iterate through all edges (u, v, w).
- If
dist[u] + w < dist[v], updatedist[v] = dist[u] + w.
- Check for Negative Cycles:
- Iterate through all edges one more time.
- If any edge can still be relaxed, a negative cycle exists.
Step-by-Step Breakdown
Watch the visualization:
- Blue edge: The edge being checked in the current pass.
- Green node: Has a finite distance from the start.
- Red edge and its two nodes: An edge that still improves a distance after V - 1 passes: a negative cycle.
- Number above a node: Its current distance from the start.
When to Use
Use Bellman-Ford when:
- The graph contains negative edge weights.
- You need to detect negative cycles (e.g., currency arbitrage).
- The graph is small enough (O(VE) is slower than Dijkstra O(E log V)).
When NOT to Use
- Positive Weights Only: Dijkstra's is significantly faster.
- Large Graphs: O(VE) complexity makes it impractical for very large networks.
How to Identify
"Shortest path with negative weights", "Detect negative cycle", "Arbitrage opportunities".
Applying for software engineering roles? Free, no sign-up:
