Zuerst das Quiz zu Kapitel 2Zuerst Kapitel 2 prüfen
Mach das Quiz zu Kapitel 2: 10 Fragen, bestanden mit 7 richtigen. Du kannst es beliebig oft wiederholen.
Dijkstra’s Frontier
Kapitel 3, Lektion 1 von 4
Shortest paths in a weighted graph, one settled vertex at a time.
Auf Englisch gesprochen. Oben kannst du englische, arabische, deutsche, spanische oder französische Untertitel einschalten.
Schriftliche Lektion
8 Min. LesezeitAuf Englisch verfasst.
In 1956 a young programmer in Amsterdam needed a demonstration for a brand new computer, and he picked a question anyone could follow: what is the shortest way to drive between two Dutch cities? Sitting on a café terrace, without pencil and paper, Edsger Dijkstra designed the answer in about twenty minutes. He published it in 1959, and the same idea still guides the maps on your phone.
His algorithm grows a frontier outwards from the start, and everything behind the frontier is settled for good. This lesson covers why breadth-first search is not enough, how the frontier grows, why its answers are final, where it breaks, and how fast it runs.
Weights matter
In breadth-first search every edge counted the same, so the fewest edges meant the shortest path. Real roads carry weights: a length, a travel time or a cost.
Here is the example from our Dijkstra guide: six places and eight roads.
| Road | A-B | A-C | C-B | B-D | C-D | D-E | D-F | E-F |
|---|---|---|---|---|---|---|---|---|
| Weight | 4 | 2 | 1 | 5 | 8 | 2 | 6 | 3 |
The direct road from A to B costs 4. Going through C costs 2 + 1 = 3. So the path with the fewest edges is not always the cheapest.
One edge costs 4, two edges cost 3.
We could list every route and keep the cheapest, but the number of routes explodes as the map grows. We need something smarter.
The frontier
Dijkstra's idea is to settle the vertices one at a time, in order of their distance from the start: the closest first, then the next closest, and so on.
At any moment every vertex is in one of three states:
- Settled: its distance is final.
- Frontier: it has a tentative distance, the cheapest route found so far.
- Unseen: no route yet, so its distance is infinity.
Each step takes the frontier vertex with the smallest tentative distance, settles it, and updates its neighbours. The frontier spreads like the ripple of breadth-first search, but it moves by distance, not by number of edges.
Settled region, frontier and unseen vertices.
The update is one small rule called relaxation. When vertex u is settled at distance d, look at each road u-v of weight w:
That remembered vertex is v's parent.
Run it by hand
Start at A with distance 0. Every other vertex starts at infinity.
| Step | Settle | Relaxations |
|---|---|---|
| 1 | A at 0 | B: ∞ → 4, C: ∞ → 2 |
| 2 | C at 2 | B: 4 → 3, D: ∞ → 10 |
| 3 | B at 3 | D: 10 → 8 |
| 4 | D at 8 | E: ∞ → 10, F: ∞ → 14 |
| 5 | E at 10 | F: 14 → 13 |
| 6 | F at 13 | none |
The shortest distances from A are B 3, C 2, D 8, E 10 and F 13. To get the route itself, follow the parents back from F: F came from E, E from D, D from B, B from C and C from A. So the cheapest route is A, C, B, D, E, F, costing 2 + 1 + 5 + 2 + 3 = 13.
The final distances, the parents, and the route to F.
Together, the parent links form a shortest-path tree rooted at A. One run answers every destination at once.
Settled is final
Why can we trust a distance the moment a vertex is settled?
Say the closest frontier vertex is v, at tentative distance d. Take any other route from the start to v. It begins inside the settled region, so at some point it leaves it for the first time, at a vertex w outside.
- Reaching w along that route costs at least w's tentative distance, because w's settled neighbour on the route already relaxed it.
- That tentative distance is at least d, because v was the closest frontier vertex.
- The rest of the route, from w to v, only adds weights of zero or more.
So no route can beat d, and v's distance is final.
The chain of inequalities behind the invariant.
The whole proof rests on one assumption in step 3: no weight is negative.
Where it breaks
Take a small directed graph: s → a costs 2, s → b costs 5, b → a costs −4 and a → t costs 1.
Dijkstra settles s at 0, then a at 2, then t at 3, then b at 5. Only then does it look at the road from b back to a. That route reaches a for 5 − 4 = 1, and t for just 2. But a and t were already declared final, so the answer 3 for t is wrong.
A negative weight arrives too late.
A tempting fix is to add 4 to every weight, so none is negative. It does not work. A route with more edges pays the extra 4 more times:
| Route | Real cost | Cost after +4 |
|---|---|---|
| s, a, t (2 edges) | 3 | 11 |
| s, b, a, t (3 edges) | 2 | 14 |
The true shortest route now looks worse, and Dijkstra happily returns s, a, t. Negative weights need a different algorithm, and that is the next lesson: Bellman-Ford.
How fast
Every step needs the frontier vertex with the smallest distance.
- A plain list. Scanning for the minimum takes time in proportion to V, and it happens V times, so the run takes O(V²). That is fine for small or very dense graphs.
- A binary heap. It hands back the minimum in O(log V). Every vertex and every edge costs at most one heap operation, so the total is O((V + E) log V).
For a road map of a million places and three million roads, V² is about 10¹², while (V + E) log V is about 8 × 10⁷: roughly twelve thousand times fewer steps.
Python's heapq cannot lower an entry that is already inside it. The usual trick is lazy deletion: push a new, smaller entry, and when the old, larger one comes out later, skip it because it is stale. On our example the heap pops nine entries and skips three stale ones: B at 4, D at 10 and F at 14.
Every pop from the heap, with the three stale entries crossed out.
The heap can now hold one entry per edge instead of one per vertex. But log E is never more than 2 log V (because E is at most V²), so the bound stays the same.
And if you only need one destination, you can stop the moment it is settled. For target D, that is after four of the six vertices.
In Python, and in the world
The whole algorithm fits in fifteen lines: a table of distances, a heap that starts with the source, and a loop that pops the closest entry, skips it if it is stale, and relaxes the neighbours.
import heapq
def dijkstra(graph, start):
distances = {node: float('inf') for node in graph}
distances[start] = 0
pq = [(0, start)]
while pq:
dist, node = heapq.heappop(pq)
if dist > distances[node]:
continue # a stale entry
for neighbour, weight in graph[node]:
new_dist = dist + weight
if new_dist < distances[neighbour]:
distances[neighbour] = new_dist
heapq.heappush(pq, (new_dist, neighbour))
return distances
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("A", 4), ("C", 1), ("D", 5)],
"C": [("A", 2), ("B", 1), ("D", 8)],
"D": [("B", 5), ("C", 8), ("E", 2), ("F", 6)],
"E": [("D", 2), ("F", 3)],
"F": [("D", 6), ("E", 3)],
}
dijkstra(graph, "A") # {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 10, 'F': 13}
The fifteen lines, and their output on the example.
Dijkstra's algorithm runs far from textbooks:
- Internet routers. In the OSPF protocol (Open Shortest Path First), every router learns the links of its network and runs Dijkstra to build its own shortest-path tree.
- Map apps. They start from the same idea, with extra tricks that prepare the road network in advance, so even a whole continent can be searched almost instantly.
- A*, the last lesson of this chapter, is Dijkstra with a sense of direction: it adds a guess of the distance still to go.
Key ideas
- Dijkstra settles the vertices in order of distance, growing a frontier outwards from the start.
- Relaxation lowers a neighbour's distance whenever a cheaper route appears, and the parents rebuild the route itself.
- A settled distance is final because no weight is negative. With a negative weight, that guarantee is gone, and adding a constant to every weight does not bring it back.
- With a binary heap it runs in O((V + E) log V); with a plain list, in O(V²).
Check yourself
1. In the example, the road C-D is lowered from 8 to 4. What is the new distance from A to F?
2. In what order does Dijkstra settle the vertices of the original example?
3. A graph has one negative edge, but it leaves the start vertex and nothing points back into the start. Is Dijkstra still safe?
Practice on the platform
The Dijkstra guide walks through this same example with the code. In the Dijkstra visualizer, import the example with its weights and run it from A: three, two, eight, ten and thirteen, the same distances we found by hand.
Als Nächstes