Sub topic 4
The Greedy Rule: Always Expand the Closest Vertex
The previous chapter showed that relaxation improves tentative distances, the current best-known distance estimates. Relaxation alone never says when an estimate is final, and it never says which vertex to process next. Dijkstra's algorithm answers both questions with one rule: always expand the unvisited vertex with the smallest tentative distance, and treat that distance as final.
This chapter assumes you know basic graph terms, adjacency lists, Big-O notation, breadth-first search (BFS), and the relaxation step from the previous chapter. A full proof of correctness comes later. Here the focus is on what the rule does, why it is plausible, and what goes wrong without it.
Three Kinds of Vertex
At any moment during the algorithm, every vertex is in one of three states:
- Settled (also called visited or finalized): its shortest distance is known and will never change.
- Frontier: it has a finite tentative distance because some settled vertex has an edge to it, but that distance may still go down.
- Unseen: no path to it has been found yet. Its tentative distance is infinity.
The greedy rule moves exactly one vertex from the frontier to the settled set on each step. After settling a vertex, the algorithm relaxes that vertex's outgoing edges. Relaxing can pull unseen vertices into the frontier and lower the distances of vertices already on it.
The settled set grows outward from the source in order of distance. The source is settled first at distance 0, then the next-closest vertex, and so on. You can picture a ripple spreading out from the source, where distance is measured by total edge weight rather than by edge count.
The Rule Without a Heap
A later chapter uses a binary heap to find the closest vertex quickly. To keep attention on the rule itself, this version finds it with a plain linear scan over all vertices. The output is the same. Only the speed differs.
def dijkstra_scan(graph, source):
"""graph: dict mapping every node -> list of (neighbor, weight), weights >= 0."""
INF = float("inf")
dist = {v: INF for v in graph}
dist[source] = 0
settled = set()
order = [] # (vertex, final distance) in the order vertices are settled
while len(settled) < len(graph):
# Greedy rule: pick the unsettled vertex with the smallest tentative distance.
u = None
for v in graph:
if v not in settled and (u is None or dist[v] < dist[u]):
u = v
if dist[u] == INF:
break # every remaining vertex is unreachable
settled.add(u)
order.append((u, dist[u]))
# Relax every outgoing edge of the newly settled vertex.
for v, w in graph[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist, order
graph = {
"A": [("B", 4), ("C", 1)],
"B": [("D", 1)],
"C": [("B", 2), ("D", 5)],
"D": [],
}
dist, order = dijkstra_scan(graph, "A")
print(order) # [('A', 0), ('C', 1), ('B', 3), ('D', 4)]
print(dist) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}The settling order prints as 0, 1, 3, 4, so the distances come out non-decreasing. That pattern always holds, and it is the clearest sign that the greedy rule is doing its job. When A is settled, B gets the estimate 4 through the direct edge. The algorithm does not settle B yet, because C has the estimate 1, which is smaller. Settling C first exposes the cheaper route A→C→B with cost 3. Only then does B become the closest unsettled vertex, and 3 is its final distance.
Why the Closest Vertex Is Safe to Finalize
Suppose u is the unsettled vertex with the smallest tentative distance dist[u]. Could some undiscovered path to u be shorter?
Any path from the source to u starts inside the settled set and has to leave it at some point. Call x the first vertex on that path outside the settled set. When the path's predecessor of x was settled, the algorithm relaxed the edge into x. So dist[x] is already at most the cost of the path up to x. Because u was the smallest choice, dist[x] >= dist[u]. The rest of the path, from x to u, uses only non-negative edges, so it adds zero or more. The whole path therefore costs at least dist[u], and no path can beat the current estimate.
The argument depends on two facts:
- The chosen vertex has the smallest tentative distance, so every other way out of the settled set starts at a cost no lower than
dist[u]. - Edge weights are non-negative, so taking a detour can never make a path cheaper.
If the first fact fails, a cheaper route may still be hidden behind a frontier vertex that has not been expanded. If the second fails, a detour through an expensive vertex followed by a negative edge can come in under dist[u]. A later chapter covers negative weights. The rest of this chapter looks at what happens when the first fact fails.
What Goes Wrong With a Different Order
BFS settles vertices in first-in, first-out (FIFO) order. On an unweighted graph, FIFO order is the same as order of distance, so BFS is correct there. With weights, the two orders differ. The function below keeps relaxation exactly as before and replaces only the selection rule with a FIFO queue:
from collections import deque
def fifo_finalize(graph, source):
INF = float("inf")
dist = {v: INF for v in graph}
dist[source] = 0
settled = set()
queue = deque([source])
while queue:
u = queue.popleft() # FIFO, not closest-first
if u in settled:
continue
settled.add(u)
for v, w in graph[u]:
if v not in settled and dist[u] + w < dist[v]:
dist[v] = dist[u] + w
queue.append(v)
return dist
graph = {
"A": [("B", 4), ("C", 1)],
"B": [("D", 1)],
"C": [("B", 2), ("D", 5)],
"D": [],
}
print(fifo_finalize(graph, "A")) # {'A': 0, 'B': 4, 'C': 1, 'D': 5}B was added to the queue before C, so B is settled at distance 4. Then C is processed and finds the cheaper route to B with cost 3, but B is already final and the update is ignored. The wrong value then spreads: D gets 5 instead of 4. One bad choice of vertex led to two wrong answers.
The table below compares common selection rules when vertices are finalized on first selection:
| Selection rule | Correct with non-negative weights? | Notes |
|---|---|---|
| Smallest tentative distance (Dijkstra) | Yes | Each vertex is settled once |
| FIFO queue (BFS order) | Only if all weights are equal | Settles by number of edges, not by total weight |
| LIFO stack (DFS order) | No | Can finalize very long paths first |
| Arbitrary order, re-process on improvement | Yes, but slow | No vertex is ever final, and work can blow up |
The last row shows the trade-off. You can drop the greedy rule and stay correct if you allow vertices to be updated and re-expanded whenever their distance improves. That approach is close to Bellman-Ford's strategy. The greedy rule is what lets Dijkstra settle each vertex exactly once.
Edge Cases of the Rule
- Ties. When two frontier vertices have the same smallest distance, either one may be settled first. Both are final, and the distances that come out do not change. The predecessor chosen for some vertex can differ, so equal-cost paths may be reported differently.
- Zero-weight edges. These are allowed. A zero edge can bring a vertex onto the frontier at the same distance as the one just settled, which creates a tie. Ties are handled as described above.
- Unreachable vertices. Once the smallest remaining distance is infinity, no remaining vertex can be reached.
dijkstra_scanstops at that point instead of "settling" vertices at infinity. - Self-loops and parallel edges. A self-loop
u→uwith weightw >= 0never improvesdist[u]. With parallel edges, relaxation keeps the cheapest one automatically. - The source. The source always comes first, at distance 0. No path can cost less than 0 when all weights are non-negative.
Cost of Finding the Closest Vertex
In dijkstra_scan, each selection scans all V vertices, and there are up to V selections, so selection costs O(V²). Each edge is relaxed once, which adds O(E). The total is O(V² + E) = O(V²). On dense graphs, where E is close to V², that bound is hard to beat. On sparse graphs, the repeated scan wastes most of its time, which is the reason for the priority queue introduced in the coming chapters.
Exercise
Run the greedy rule by hand from S on this directed graph: S→X (weight 2), S→Y (weight 6), X→Y (weight 3), X→Z (weight 7), Y→Z (weight 1). List the vertices in the order they are settled, with their final distances.
Show answer
S at 0, X at 2, Y at 5 (through X, which beats the direct 6), Z at 6 (through Y, which beats 2 + 7 = 9). The order is S(0), X(2), Y(5), Z(6), and the distances never decrease.
Exercise
Using the same graph, which vertex would FIFO order (fifo_finalize) settle with a wrong distance, and what wrong value would it record?
Show answer
The queue starts with S. Settling S sets X = 2 and Y = 6 and adds both to the queue. Settling X lowers Y to 5 and adds it again, and sets Z = 9. Next comes the first queued copy of Y, now at 5. Settling Y lowers Z to 6. Here Y happens to be correct because its distance improved before it was dequeued, and Z ends at 6, which is also correct. This graph does not trigger the bug. The failure only appears when a vertex is dequeued before a cheaper route to it has been relaxed, as with B in the chapter's example.
Exercise
Explain in one or two sentences why the sequence of distances at which vertices are settled must be non-decreasing when all weights are non-negative.
Show answer
Settling u can only set its neighbors to dist[u] + w with w >= 0, which is no smaller than dist[u]. Every vertex left on the frontier already had a distance of at least dist[u], so the next minimum cannot be below dist[u].