Three grid problems where a heap is more than you need. The move: match the queue to the step costs, and put every start in before the first pop.
You work on a building map, a warehouse planner and a city map. The three problems on this street ask for the shortest route on a grid. The costs are so simple that the heap from Dijkstra's method is more than you need.
Read the table by its last two columns. They decide the queue.
| Problem | The starts | A step costs | The queue |
|---|---|---|---|
| Nearest exit from the maze | the robot's cell | 1 for every step | rings, one for each distance |
| Shortest bridge between two islands | every block of one zone | 1 for each uncovered block | rings from all starts at once |
| Fewest obstacle removals | one corner | 0 for an empty cell, 1 for a stand | a deque, free cells to the front |
When you read a new grid problem, write those two columns first. Then pick the queue.
Exercise · Predict the output: Free cells jump the queue. A deque holds the cells to visit. A step into an empty cell costs 0 and goes to the front. A step into a stand costs 1 and goes to the back. What does this print?
from collections import deque
layout = [[0, 1, 1, 0], [1, 1, 0, 0], [1, 0, 0, 0]]
rows, cols = 3, 4
dist = [[99] * cols for _ in range(rows)]
dist[0][0] = 0
queue = deque([(0, 0)])
while queue:
r, c = queue.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and dist[r][c] + layout[nr][nc] < dist[nr][nc]:
dist[nr][nc] = dist[r][c] + layout[nr][nc]
if layout[nr][nc] == 0:
queue.appendleft((nr, nc))
else:
queue.append((nr, nc))
print(dist[2][3])Two questions decide the search, and you can answer both from the statement.
First, which step costs are possible? Second, how many starts are there? The first picks the queue. The second decides what goes in before the first pop.
| Step costs | The queue | Why the front is final |
|---|---|---|
| all 1 | a plain queue, one ring for each distance | cells enter in order of distance |
| 0 and 1 | a deque: cost 0 to the front, cost 1 to the back | the front always holds the lowest cost |
| many different costs | a heap | the heap sorts them |
The queue holds cells in non-decreasing order of cost, and every start is in it at cost 0. So the cell at the front is final, and no heap is needed.
Many starts cost nothing extra. Mark every start as seen and push them all before the first pop. The search then behaves as if a hidden start joined them all with free roads.
The same idea explains the stop. Cells leave the queue in order of cost, so the first ring that holds a target is the nearest one. Every other target in that ring is equally near, which matters when the question asks how many.
In a deque ordered by cost, a free step goes to the front and a costly step goes to the back, so the front is always final.
Exercise · Find the bug: A free cell waits at the back. A walk through a floor of empty cells (0) and stands (1) pays 1 for each stand it enters. The queue is a deque. Which line is wrong?
from collections import deque
def fewest_stands_moved(layout):
rows, cols = len(layout), len(layout[0])
dist = [[10**9] * cols for _ in range(rows)]
dist[0][0] = 0
queue = deque([(0, 0)])
while queue:
r, c = queue.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == 10**9:
dist[nr][nc] = dist[r][c] + layout[nr][nc]
if layout[nr][nc] == 0:
queue.append((nr, nc))
else:
queue.append((nr, nc))
return dist[rows - 1][cols - 1]The Academy lesson BFS and DFS on a grid walks a grid ring by ring. Dijkstra's shortest paths keeps a heap for costs that differ. This street does not teach them again. It changes three things.
The heap leaves. When every cost is 0 or 1, a deque keeps the cells in order. The heap pays about 16 levels for each push and pop on a grid of 90,000 cells, because the base-2 logarithm of 90,000 is 16.5. The deque pays one step.
Many starts become one search. Take a 60 by 60 grid with a zone of 100 blocks. One search that starts from all 100 blocks visits 3,438 cells before it reaches the other zone. A search from each block visits 343,800 in total, which is 100 times as many.
The ring is the answer. In nearest exit the search stops at the first ring that holds a door, and it counts every door in that ring. Stopping at the first door found gives the right distance and the wrong count.
Plain breadth-first search is not enough for stands. On the floor [[0,0,0],[0,0,0],[0,1,0]] a plain queue returns 1 stand moved, and the right answer is 0.
A plain queue orders cells by steps, not by cost. With stands it can return 1 where the answer is 0.
Exercise · Break it: Count the doors in the ring. This returns the fewest steps to a door and the number of doors at that distance. It stops as soon as it sees a door. Find an input where it gives the wrong count.
def nearest_exits(plan, row, col):
rows, cols = len(plan), len(plan[0])
seen = {(row, col)}
ring = [(row, col)]
steps = 0
while ring:
steps += 1
nxt = []
for r, c in ring:
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and plan[nr][nc] == "." and (nr, nc) not in seen:
if nr in (0, rows - 1) or nc in (0, cols - 1):
return [steps, 1]
seen.add((nr, nc))
nxt.append((nr, nc))
ring = nxt
return [-1, 0]Solve them in this order. The first uses rings from one start, the second rings from many starts, and the third needs the deque.
Before you code each problem, write two lines: the possible step costs, and the number of starts. The first line picks the queue, and the second decides what goes in before the first pop.
Give each problem about 25 minutes. Spend the first four on the two lines, and say them aloud as you would to an interviewer. Then write what the search returns when no target is reachable.
Three edge cases return on every rung. The start may already be a target, and the problem may say whether that counts. Two starts may touch, so mark them all seen first. A grid of one cell has no steps to take.
When a solution fails, check the queue before the loop. Most wrong answers on this street come from a free cell that waits at the back, or from a start that was not marked seen.
Checkpoint · Zero one and multi source
Q1/5 Every step on a grid costs 1. Which queue gives the shortest routes in order?
Answer: B
Cells enter a plain queue in order of distance, so the front is always final. A heap is more than the costs need.
Q2/5 Steps cost 0 into an empty cell and 1 into a stand. Where does a newly reached empty cell go in the deque?
Answer: B
The deque must hold cells in non-decreasing cost. A cell with the same cost as the one taken before it belongs before cells that cost more.
Q3/5 A zone has 100 blocks and you need the distance to a second zone. What is the efficient way to start?
Answer: B
One search from all blocks visits each cell once. A search from each block repeats the same work, 100 times over in the lesson's example.
Q4/5 A robot stands in a room with four doors, each one step away. What must nearest exit return?
Answer: B
The whole first ring is at distance 1, so all four doors count. Stopping at the first door found gives the wrong count.
Q5/5 On the floor [[0,0,0],[0,0,0],[0,1,0]], why can a plain queue return 1 instead of 0?
Answer: B
A plain queue is correct only when every step costs the same. With costs 0 and 1 it needs the deque, which keeps cells in order of cost.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.