Four interview problems that count steps. The move: seed the queue with every start, spread one ring at a time, and let the first visit set the distance.
You work on a warehouse robot planner, a shop's stock room and a search app. The four problems on this street ask for the fewest steps from somewhere to somewhere. The tool is breadth-first search, and you know it from the Academy. The problems change what goes into the queue first and what a step is.
| Problem | The queue starts with | One step is | The answer is |
|---|---|---|---|
| Distance to the nearest zero | every charging station | a move up, down, left or right | each cell's distance |
| Which dock serves each bay | the docks of both teams | a move onto a bay that is not shelving | bays per team, ties, last minute |
| Drone route between racks | the top-left bay | one of eight moves, with a squeeze rule | the fewest moves, or -1 |
| Word ladder length | the begin word | change one letter to an indexed term | the fewest changes, or -1 |
Read the second column first. The first two problems start from many cells at once. The last two start from one, but their steps are not the plain four moves.
Exercise · Predict the output: How many cells are two moves away?. A grid has 3 rows and 4 columns. Two stations stand at row 0, column 0 and at row 2, column 3. The code fills each cell with the number of moves to the nearest station. How many cells hold the value 2?
rows, cols = 3, 4
dist = [[-1] * cols for _ in range(rows)]
queue = [(0, 0), (2, 3)]
for r, c in queue:
dist[r][c] = 0
head = 0
while head < len(queue):
r, c = queue[head]
head += 1
for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
print(sum(row.count(2) for row in dist))The queue always holds the cells at distance d first and the cells at distance d + 1 after them. A cell leaves the queue in order of distance. So the first time the search reaches a cell, it has used the fewest steps.
That gives two habits.
The queue holds cells at distance d, then cells at distance d + 1. So the first visit to a cell is by a shortest path. With every start queued at distance 0, each cell gets its distance to the nearest start.
The seed matters for cost. For a 30 by 30 floor with one station in the far corner, a separate search from each cell makes 596,165 visits. One search seeded with the stations makes 900.
Put every station in the queue at distance 0, then spread ring by ring: one search gives each bay its distance to the nearest station.
Rings also matter for ties. When two teams spread at the same time, a bay belongs to a team only if no other team reaches it in the same ring. So you collect one ring's claims before you mark them. On the row 2 0 0 0 3, the two docks each serve their own dock and the bay next to it, and the middle bay is contested at minute 2.
Exercise · Find the bug: One minute too many. This spreads from every dock ring by ring, and returns the minute when the last open bay is first reached. It counts a minute at the end of every ring. Which line is wrong?
def last_minute(floor):
rows, cols = len(floor), len(floor[0])
frontier = [(r, c) for r in range(rows) for c in range(cols) if floor[r][c] == 2]
seen = set(frontier)
minutes = 0
while frontier:
nxt = []
for r, c in frontier:
for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and floor[nr][nc] == 0 and (nr, nc) not in seen:
seen.add((nr, nc))
nxt.append((nr, nc))
frontier = nxt
minutes += 1
return minutesThe Academy lesson BFS and DFS on a grid finds the shortest path from one start. BFS and DFS on any graph does the same on links and on states such as lock codes. This street changes three things.
More than one start. Seeding all the sources is one change in the setup, and the loop stays the same. For two teams you also keep the ring: take all claims of one ring, then mark them.
On the row 2 0 0 3 there are 2 bays for each team and none contested. On 2 0 0 0 3 the middle bay is contested at minute 2.
A step that is not four moves. The drone moves in eight directions. A diagonal move is blocked when both bays beside it hold racks.
On the grid 0 1 / 1 0 the corner-to-corner move is blocked, so the answer is -1. Without the squeeze rule it would be 1.
Neighbours that nobody stores. In the word ladder the nodes are words. Make the neighbours by changing each letter to each other letter and looking the result up in a set.
Take a list of 4,635 distinct five-letter words. Comparing every pair costs 10,739,295 comparisons, and generating the neighbours costs 579,375 lookups. With the terms cord, card, ward, warm, wood and word, the chain from cold to warm has 4 steps.
One check comes before every search: is the start allowed, and is the goal allowed? A start on a rack has no route, and a goal that is not in the term list has none either.
Exercise · Break it: The start that is a rack. This returns the fewest moves from the top-left bay to the bottom-right bay on a grid where 1 is a rack. It spreads from the start in four directions. Find an input where it gives the wrong answer.
def fewest_moves(grid):
rows, cols = len(grid), len(grid[0])
dist = [[-1] * cols for _ in range(rows)]
dist[0][0] = 0
queue = [(0, 0)]
for r, c in queue:
for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0 and dist[nr][nc] == -1:
dist[nr][nc] = dist[r][c] + 1
queue.append((nr, nc))
return dist[rows - 1][cols - 1]Check the start before you search: a start on a rack has no route, even when it is also the goal.
Solve them in this order. The first seeds many starts. The second adds a second team and ties. The third changes what a step is, and the last has no grid at all.
Before you code each problem, write three lines: what goes in the queue first, what one step is, and what the answer reads. For the last two, also write what makes a start or a goal invalid.
Give each problem about 25 minutes. Draw a small example and write the ring number in each cell by hand before you code.
Then write three small tests: a start that is also the goal, a start that is blocked, and a grid where the goal cannot be reached. A BFS that answers all three is usually correct.
When an answer is wrong by one, check where you add the step: when a cell joins the queue, or when a ring ends. Most wrong answers here come from an extra ring or a missing seed.
Checkpoint · BFS and shortest steps
Q1/5 Why is the first visit to a cell in a BFS also its shortest distance?
Answer: B
The queue order is what makes the first visit shortest. Each cell joins one step after the cell that found it.
Q2/5 A floor has several charging stations. You need each cell's distance to the nearest one. What is the cheapest plan?
Answer: C
A single seeded search gives each cell the distance to its nearest station. On a 30 by 30 floor with one far station, a search from every cell makes 596,165 visits and the seeded search 900.
Q3/5 Two teams spread from their docks at the same time. When is a bay contested?
Answer: C
Collect the claims of a whole ring before you mark them. A bay with two claims in one ring is contested, and a bay with one claim belongs to that team.
Q4/5 A BFS counts a minute at the end of every ring. For a row of one dock and two open bays, it returns 3. What is the right answer?
Answer: C
The last open bay is reached at minute 2. The ring that starts there finds nothing new, so it should not add a minute.
Q5/5 In the word ladder, why make a word's neighbours by changing each letter and looking the result up in a set?
Answer: C
For 4,635 five-letter words, comparing every pair costs 10,739,295 comparisons, and generating the neighbours costs 579,375 lookups.
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.