Dijkstra vs Bellman-Ford
Dijkstra and Bellman-Ford are both shortest path. Play them side by side below, then see exactly where they diverge.
Either player can stop before each decision and ask what happens next: turn on Predict mode in its top bar.
Dijkstra
Full topicRepeatedly settle the unsettled vertex with the smallest tentative distance and relax its edges.
SELECT MINIMUM -> RELAX neighbours -> UPDATE distances. Settled vertices lock. The priority queue is visible.
Bellman-Ford
Full topicRelax every edge V-1 times. A further improvement means a negative cycle.
Whole-graph relaxation passes. Distances settle pass by pass. A V-th pass that changes anything flags a negative cycle.
How they differ
Both find shortest paths from one source by relaxing edges. They differ in how many times. Dijkstra settles the closest unsettled vertex and relaxes its edges once, which is O((V + E) log V) with a binary heap, and it requires non-negative weights. Bellman-Ford relaxes every edge V-1 times, O(V * E), and handles negative weights instead - a further pass that still improves a distance means a negative cycle.
The run shown here takes 13 steps for Dijkstra and 9 steps for Bellman-Ford (Bellman-Ford from 0). That count moves with the input - use the example tabs above either player to see it change.
| Cost | Dijkstra | Bellman-Ford |
|---|---|---|
| best | O((V + E) log V) | O(E) |
| average | O((V + E) log V) | O(V * E) |
| worst | O((V + E) log V) | O(V * E) |
| space | O(V) | O(V) |