Dijkstra's Algorithm
When every edge weight is non-negative, there is a much faster way to get single-source shortest paths than Bellman-Ford. Dijkstra's algorithm (1959) grows a set of vertices whose distances are final, like a breadth-first search that measures distance in weight instead of in edges. At every step it picks the vertex outside with the smallest estimate, declares that estimate final, and relaxes the edges leaving it. Every edge is relaxed exactly once, as in the DAG algorithm, but the order comes from a priority queue instead of a topological sort. Route planners, network routing protocols such as OSPF and IS-IS, and countless game engines use it. The DSA course has a first look; this lesson states it precisely, and the next two prove it correct and analyse its running time.
The algorithm
DIJKSTRA(G, w, s) // requires w(u, v) >= 0 for every edge
1 INITIALIZE-SINGLE-SOURCE(G, s)
2 S = empty set
3 Q = a min-priority queue of all vertices, keyed by their d values
4 while Q is not empty
5 u = EXTRACT-MIN(Q) // the closest vertex not yet final
6 S = S + {u}
7 for each v in G.Adj[u]
8 RELAX(u, v, w) // a decrease of v.d is a DECREASE-KEY in QIt looks almost exactly like Prim's algorithm. The only difference is the key: Prim keys a vertex by the weight of the single edge connecting it to the tree, Dijkstra by the length of the whole path from .
Watching it work
The graph is a small road network; weights are travel times in minutes. Labels show the current estimates.
The Python version uses heapq with lazy deletion: when an estimate decreases it pushes a new entry, and entries for vertices already in are skipped when popped. Entries are (distance, name) pairs, so ties are broken by name, as in the animation. It prints the same steps.
import heapq
edges = [("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", 2), ("E", "G", 7), ("F", "G", 3)]
adj = {v: [] for v in "ABCDEFG"}
for u, v, w in edges:
adj[u].append((v, w)); adj[v].append((u, w))
for v in adj:
adj[v].sort()
def dijkstra(adj, s):
INF = float("inf")
d = {v: INF for v in adj}
pi = {v: None for v in adj}
d[s] = 0
done = set()
pq = [(0, s)]
while pq:
du, u = heapq.heappop(pq)
if u in done:
continue # stale entry
done.add(u)
print(f"settle {u} at distance {du}")
for v, w in adj[u]:
if v in done:
continue
if du + w < d[v]:
print(f" relax {u}->{v}: {du} + {w} = {du + w} < {d[v]}, update")
d[v], pi[v] = du + w, u
heapq.heappush(pq, (d[v], v))
else:
print(f" {u}->{v}: {du} + {w} = {du + w} is not better than {d[v]}")
return d, pi
d, pi = dijkstra(adj, "A")
print("distances:", d)
def path(v):
return path(pi[v]) + [v] if pi[v] else [v]
print("route to G:", " -> ".join(path("G")), f"({d['G']} minutes)")settle A at distance 0
relax A->B: 0 + 4 = 4 < inf, update
relax A->C: 0 + 2 = 2 < inf, update
settle C at distance 2
relax C->B: 2 + 1 = 3 < 4, update
relax C->D: 2 + 8 = 10 < inf, update
relax C->E: 2 + 10 = 12 < inf, update
settle B at distance 3
relax B->D: 3 + 5 = 8 < 10, update
settle D at distance 8
relax D->E: 8 + 2 = 10 < 12, update
relax D->F: 8 + 6 = 14 < inf, update
settle E at distance 10
relax E->F: 10 + 2 = 12 < 14, update
relax E->G: 10 + 7 = 17 < inf, update
settle F at distance 12
relax F->G: 12 + 3 = 15 < 17, update
settle G at distance 15
distances: {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 12, 'G': 15}
route to G: A -> C -> B -> D -> E -> F -> G (15 minutes)
The vertices are settled in the order , which is also the order of their final distances . That is no accident: Dijkstra's algorithm settles vertices in non-decreasing order of distance, the fact at the heart of its correctness proof. Notice also : its first estimate 4 (directly from ) is improved to 3 by the detour through , before is settled.
In C++
The standard C++ version uses std::priority_queue with std::greater, which turns it into a min-heap, and the same lazy deletion.
#include <climits>
#include <cstdio>
#include <functional>
#include <queue>
#include <utility>
#include <vector>
int main() {
const int n = 7; // A..G
struct E { char u, v; int w; };
std::vector<E> edges = {{'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',2}, {'E','G',7}, {'F','G',3}};
std::vector<std::vector<std::pair<int, int>>> adj(n);
for (auto e : edges) {
adj[e.u - 'A'].push_back({e.v - 'A', e.w});
adj[e.v - 'A'].push_back({e.u - 'A', e.w});
}
std::vector<long long> d(n, LLONG_MAX);
std::vector<int> pi(n, -1);
using Item = std::pair<long long, int>; // (distance, vertex)
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
d[0] = 0;
pq.push({0, 0});
while (!pq.empty()) {
auto [du, u] = pq.top();
pq.pop();
if (du > d[u]) continue; // stale entry
for (auto [v, w] : adj[u])
if (du + w < d[v]) { d[v] = du + w; pi[v] = u; pq.push({d[v], v}); }
}
for (int v = 0; v < n; ++v)
std::printf("%c: %lld via %c\n", 'A' + v, d[v], pi[v] < 0 ? '-' : 'A' + pi[v]);
}A: 0 via -
B: 3 via C
C: 2 via A
D: 8 via B
E: 10 via D
F: 12 via E
G: 15 via F
The test du > d[u] is the usual C++ way to detect a stale entry without a separate "done" set: an entry is stale exactly when a smaller distance for the same vertex was recorded after it was pushed.
Why negative weights break it
Dijkstra declares a vertex final the moment it is extracted. With non-negative weights no later path can be shorter, since any path that leaves only gets longer. A negative edge invalidates that reasoning. In the graph below, is settled at distance 2, but the path costs .
import heapq
def dijkstra(adj, s):
d, done, pq = {v: float("inf") for v in adj}, set(), [(0, s)]
d[s] = 0
while pq:
du, u = heapq.heappop(pq)
if u in done:
continue
done.add(u)
for v, w in adj[u]:
if v not in done and du + w < d[v]:
d[v] = du + w
heapq.heappush(pq, (d[v], v))
return d
def bellman_ford(adj, s):
d = {v: float("inf") for v in adj}
d[s] = 0
for _ in range(len(adj) - 1):
for u in adj:
for v, w in adj[u]:
d[v] = min(d[v], d[u] + w)
return d
adj = {"A": [("B", 2), ("C", 5)], "B": [("D", 1)], "C": [("B", -4)], "D": []}
print("Dijkstra: ", dijkstra(adj, "A"))
print("Bellman-Ford:", bellman_ford(adj, "A"))Dijkstra: {'A': 0, 'B': 2, 'C': 5, 'D': 3}
Bellman-Ford: {'A': 0, 'B': 1, 'C': 5, 'D': 2}
Dijkstra settles at 2 and at 3, and when later offers a value of 1, is already final and the improvement is never propagated to . Bellman-Ford gets and . Adding a constant to every weight to make them non-negative does not fix this either: it penalizes paths with many edges. The correct reweighting, which preserves shortest paths, is Johnson's.
Running time in brief
Each vertex is extracted once and each edge relaxed once. With a binary heap, extractions and up to decrease-keys (or pushes, with lazy deletion) cost each, for , which is when every vertex is reachable. Dijkstra with Different Priority Queues compares this with an array () and a Fibonacci heap (). Practise with Shortest Distances.
Test yourself
What is the essential difference between Dijkstra's and Prim's algorithms?
- Dijkstra uses a stack
- Dijkstra keys a vertex by the length of the whole path from the source, Prim by the weight of one connecting edge
- Prim allows negative weights
- There is none
In which order does Dijkstra's algorithm settle vertices?
- Alphabetical
- In non-decreasing order of their final distance from
- In BFS order
- In order of degree
Why does adding a constant to every weight not make Dijkstra correct on graphs with negative edges?
- It makes weights fractional
- It changes which path is shortest, because a path with edges gains times the constant
- It creates negative cycles
- It does make it correct