Sub topic 4
The Greedy Rule: Always Expand the Closest Vertex
This chapter assumes you know what edge relaxation is from the previous chapter. You should also be comfortable with adjacency lists stored as Python dicts and with breadth-first search. Relaxation tells you how to improve a distance estimate. It does not tell you which vertex to relax from next. Dijkstra's algorithm answers that question with one greedy rule.
The rule
At every step, pick the unvisited vertex with the smallest tentative distance. Mark it visited, which means its distance is now final. Then relax every edge leaving it.
That is the whole algorithm. Everything else is bookkeeping and data structures.
A greedy algorithm makes the locally best choice at each step and never reconsiders it. Many greedy algorithms produce wrong answers. This one is correct as long as every edge weight is non-negative. A later chapter proves this. Here is the intuition. Suppose u is the closest unvisited vertex, at distance d. Any other route to u must leave the visited set through some unvisited vertex x. Because u was chosen, x is already at distance d or more. Edges cannot have negative weight, so continuing from x to u can only add cost. No unexplored route can beat d.
Comparing it with BFS
BFS is the same idea on an unweighted graph. BFS processes vertices in order of hop count, and its FIFO queue keeps them in that order with no extra work. When edges have weights, the order in which vertices are discovered no longer matches the order of their distances. A vertex reached later through cheap edges can be closer than one reached earlier through one expensive edge. Dijkstra replaces "first discovered" with "smallest tentative distance."
A direct implementation
The simplest way to apply the rule is a linear scan over all vertices. This takes O(V) time per selection, so O(V²) in total. Later chapters replace the scan with a heap, but the rule stays the same.
def closest_unvisited(dist, visited):
best, best_d = None, float("inf")
for v, d in dist.items():
if v not in visited and d < best_d:
best, best_d = v, d
return best # None when nothing reachable is left
def dijkstra_simple(graph, source):
"""graph: dict node -> list of (neighbor, weight); every node is a key."""
dist = {v: float("inf") for v in graph}
dist[source] = 0
visited = set()
while True:
u = closest_unvisited(dist, visited)
if u is None:
break
visited.add(u)
for v, w in graph[u]:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
graph = {
"A": [("B", 4), ("C", 1)],
"C": [("B", 2), ("D", 5)],
"B": [("D", 1)],
"D": [],
}
print(dijkstra_simple(graph, "A")) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}The rule matters in this example. After visiting A, B has tentative distance 4 and C has 1. The algorithm picks C because it is closer. Relaxing C → B lowers B to 3. If the algorithm had finalized B at 4 first, that answer would have been wrong.
Common mistakes
| Mistake | Effect |
|---|---|
| Selecting by discovery order (a FIFO queue) | Vertices get finalized before cheaper routes to them are found |
| Selecting by smallest edge weight instead of total distance | Ignores the cost of reaching the edge's start vertex |
| Relaxing edges into already-visited vertices and treating the update as meaningful | With non-negative weights this never improves anything. If it does, a negative edge is present |
| Looping until all vertices are visited | Unreachable vertices stay at infinity, so stop when the closest remaining distance is infinite |
Exercise
In the example graph, change the weight of edge C → B from 2 to 4. Which vertex does the algorithm visit second and which third, and what is the final distance to D?
Show answer
After A, C (distance 1) is visited second. Relaxing C gives B = min(4, 1+4) = 4 and D = 1+5 = 6. B (4) is closer than D (6), so B is visited third. Relaxing B → D gives 4+1 = 5, so D's final distance is 5.
Exercise
Why does Dijkstra select by tentative distance rather than by the weight of the cheapest outgoing edge?
Show answer
The cost of a path is the total of all its edges, starting from the source. A cheap edge leaving a vertex that is far from the source can still lead to a long path. Only the tentative distance accounts for the cost of getting to the vertex.