Sub topic 12
Cheapest Paths with Dijkstra
This chapter assumes you can write a breadth-first search (BFS) with a queue, use a dictionary and a set, and have a basic idea of what a heap is. It builds on the grid neighbour function and on edge costs from the previous chapter.
Why BFS is not enough
BFS finds the path with the fewest edges. That is the cheapest path only when every move costs the same. If entering a swamp costs 5 and entering a road costs 1, the path with the fewest steps may cost more than a longer path along roads.
Dijkstra's algorithm fixes this. It always expands the cell with the smallest known total cost so far. It needs one rule: no edge cost may be negative. With non-negative costs, the first time a cell is removed from the priority queue, its cost is final.
The working model
Keep three things:
best: a dictionary that maps each cell to the cheapest total cost found so far.heap: a priority queue of(total_cost, cell)pairs. Python'sheapqalways pops the smallest pair.- A rule for updates: when a cheaper route to a neighbour appears, record it and push the neighbour again.
The code
Here each number in cost is the price of entering that cell, and None marks a wall.
import heapq
def cheapest_cost(cost, start, goal):
rows, cols = len(cost), len(cost[0])
best = {start: 0}
heap = [(0, start)]
while heap:
dist, cell = heapq.heappop(heap)
if cell == goal:
return dist
if dist > best[cell]:
continue
r, c = cell
for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and cost[nr][nc] is not None:
nd = dist + cost[nr][nc]
if nd < best.get((nr, nc), float('inf')):
best[(nr, nc)] = nd
heapq.heappush(heap, (nd, (nr, nc)))
return None
grid = [
[1, 1, 1],
[9, 9, 1],
[1, 1, 1],
]
print(cheapest_cost(grid, (0, 0), (2, 0)))The program prints 6. The short route down the left column would cost 9 + 1 = 10. The longer route along the top, down the right side, and back along the bottom costs 1 + 1 + 1 + 1 + 1 = 5 to reach (2, 2), and then 1 + 1 = 2 more to reach (2, 0). That makes 7, so check the first two cells: (0, 1) costs 1, (0, 2) costs 1, (1, 2) costs 1, (2, 2) costs 1, (2, 1) costs 1, (2, 0) costs 1. The total is 6.
Stale entries
The heap cannot update an entry in place. When a cheaper route to a cell is found, the older, more expensive entry stays in the heap. The check if dist > best[cell]: continue discards those stale entries when they surface. Without it, the code still returns correct answers but repeats work.
Common errors
- Negative costs. Dijkstra can return wrong answers. Use a different algorithm, such as Bellman-Ford.
- Returning too early. Return when the goal is popped, not when it is first pushed. The first push may not be the cheapest route.
- Comparing cells on ties. Heap entries are tuples. If two costs tie, Python compares the cells next. Tuples of integers compare fine, but cell objects that cannot be ordered raise a
TypeError. - Wrong cost placement. Decide whether the cost belongs to the cell entered or to the edge. Mixing the two double-counts or skips costs.
Relation to BFS
Dijkstra with every cost equal to 1 behaves like BFS, but it pays the log n price of the heap. If all costs are equal, use BFS. To rebuild the path, store a parent dictionary as you did in BFS, updating it whenever best changes.
Exercise
In the grid above, the cell (1, 0) costs 9. Suppose the goal is (2, 0) and you change (1, 0) to 1. What does cheapest_cost return, and why?
Show answer
It returns 2. The route (0, 0) to (1, 0) to (2, 0) now costs 1 + 1 = 2, which beats the 6 of the longer route. Dijkstra pops (2, 0) with cost 2 before any more expensive entry.