Five interview problems that walk a grid. The move: fix the neighbour rule, the places the walks start and what each walk reports before you write the loop.
You work on a photo editor, a ride-hailing app, a shop's stock system, a data-hall monitor and a maps app. The five problems on this street all walk a grid. The walk is the one you know from the Academy. The problems differ in what they ask the walk to do.
Each row of this table gives the three choices that define the problem.
| Problem | Two cells are neighbours when | The walks start at | A walk reports |
|---|---|---|---|
| Gradient fill for a photo editor | the shades differ by at most tol | the tapped pixel | the pixels it painted |
| Blocks of stock on a carousel | they share a side, and the last column touches the first | every unseen stock bay | one more block |
| Largest zone | they share a side | every unseen busy cell | its cell count |
| Sensors cut off from every gateway | they share a side or a corner | every open edge cell | the cells it reached |
| Which cells drain to both edges | water can flow from one to the other | the cells of one river's edge | the cells it reached |
Read the middle column first. It is the only part that changes the way you write the neighbour loop. The other two columns change what you do around the walk.
Here is the first trap. The rule for a neighbour can look at two cells, not one.
Take the shades 100, 110, 120, 130, 140, 250 with a tolerance of 10. Comparing each pixel with its neighbour fills five pixels from the left end. Comparing every pixel with the tapped one fills only two.
Exercise · Predict the output: How many neighbours at the corner?. A grid has 3 rows and 4 columns, and the last column touches the first. The code counts the neighbours of the cell in row 0, column 3, diagonals included. What does it print?
rows, cols = 3, 4
r, c = 0, 3
count = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
nr = r + dr
nc = (c + dc + cols) % cols
if (dr != 0 or dc != 0) and 0 <= nr < rows:
count += 1
print(count)Before any code, answer three questions on paper.
Then write the walk once and keep it fixed. The cell is marked when it joins the frontier, not when it leaves. Each cell therefore enters once, and the work is proportional to the number of cells.
A walk from one start reaches exactly the cells joined to it by the neighbour rule. A cell is marked when it is queued, so each cell enters once and a walk costs about one visit per cell.
The three answers also decide the cost. Look at the drain problem. Rain flows downhill, so the obvious plan is to follow the water from each cell and see which river it reaches. That is one walk per cell.
The better plan reverses the direction. Start at the first river's edge and climb to every cell whose water could have come from there. Do the same from the second river, and keep the cells in both sets.
Walk uphill from each river's edge: two walks replace a downhill walk from every cell.
Exercise · Find the bug: Climb, not slide. This walks from the first river's edge (row 0 and column 0) and counts the cells whose rain can reach it. The code runs and ends, but the count is wrong on some maps. Which line is wrong?
def count_reaching_first_river(heights):
rows, cols = len(heights), len(heights[0])
seen = [[r == 0 or c == 0 for c in range(cols)] for r in range(rows)]
stack = [(r, c) for r in range(rows) for c in range(cols) if seen[r][c]]
count = len(stack)
while stack:
r, c = stack.pop()
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 not seen[nr][nc]:
if heights[nr][nc] <= heights[r][c]:
seen[nr][nc] = True
stack.append((nr, nc))
count += 1
return countThe Academy lesson BFS and DFS on a grid walks open cells in four directions and counts the cells reached. It also covers the queue, the stack and the cost of O(rows × columns). Read Graphs for the idea that a grid is a graph. This street changes three things instead.
The neighbour rule is yours to write. The carousel problem wraps round: the neighbour's column is (c + dc + cols) % cols. Take this grid of stock, with 1 for a full bay.
1 0 0 1 1
0 0 0 0 0
0 1 1 0 0
1 0 0 0 1With the wrap it has 3 blocks. Without the wrap it has 5, because the ends of the rows are cut apart.
The sensor problem adds the four diagonals. On one 5 by 5 hall, two inner open cells reach the edge only through a corner link. A four-direction walk reports 2 cut-off cells, and the right answer is 0.
The start can be the answer's side. For the drain problem on a grid of equal heights, a downhill walk from every cell makes 810,000 visits on a 30 by 30 map. The two uphill walks make 1,800. At 300 by 300 the first plan needs 8.1 billion visits and the second 180,000.
A walk can report more than a count. It can report its size, the cells it reached, or a painted copy. Painting needs one more rule: compare the original shades only, so a painted cell does not change how its neighbours are judged.
One habit holds on every rung. Check the bounds before you read a cell, and mark a cell when you add it to the frontier.
Exercise · Break it: The carousel that does not turn. This counts the blocks of full bays on a carousel, where the last column touches the first. It walks four directions with an explicit stack. Find an input where it gives the wrong count.
def count_blocks(bays):
rows, cols = len(bays), len(bays[0])
seen = [[False] * cols for _ in range(rows)]
blocks = 0
for r in range(rows):
for c in range(cols):
if bays[r][c] == 1 and not seen[r][c]:
blocks += 1
seen[r][c] = True
stack = [(r, c)]
while stack:
cr, cc = stack.pop()
for dr, dc in ((-1, 0), (0, 1), (1, 0), (0, -1)):
nr, nc = cr + dr, cc + dc
if 0 <= nr < rows and 0 <= nc < cols and bays[nr][nc] == 1 and not seen[nr][nc]:
seen[nr][nc] = True
stack.append((nr, nc))
return blocksOn a carousel the last column touches the first. Take the neighbour column with a remainder, or the walk misses blocks.
Solve them in this order. The first is a plain walk with a rule on the pair. The next two change the neighbours or the report, and the last two change where the walks start.
Before you code each problem, write the three answers: the neighbour rule, the starts and the report. Say them aloud as you would to an interviewer. If you cannot name the starts, the problem is not ready to code.
Give each problem about 25 minutes. Spend the first four on the three answers and a 3 by 3 example drawn by hand.
Then write three small tests before you run anything: a grid with one row, a grid with one column and a grid with no cell that qualifies. These break more grid walks than any large input does.
When an answer is wrong, check the neighbour rule before the loop. Most wrong answers on this street come from a missing wrap, a missing diagonal, or a test that compares the wrong two cells.
Checkpoint · Grid traversal
Q1/5 Which three choices should you write down before the loop of a grid-walk problem?
Answer: B
The walk itself stays the same. These three choices are what differ from one problem to the next.
Q2/5 The last column touches the first. What is the column of the right-hand neighbour of column c in a grid with cols columns?
Answer: B
The remainder sends the last column back to column 0. For the left-hand neighbour write (c - 1 + cols) % cols, so the number never goes negative.
Q3/5 Signals pass between open cells that touch by a side or by a corner. What happens if you walk four directions only?
Answer: C
A diagonal link is a neighbour in this problem. Leaving it out splits groups that are really joined.
Q4/5 Why does the drain problem walk uphill from the two river edges instead of downhill from every cell?
Answer: C
On a 30 by 30 map of equal heights, the downhill plan makes 810,000 visits and the two uphill walks make 1,800.
Q5/5 When should a cell be marked as seen in a grid walk?
Answer: B
Marking on entry means a cell is queued once. Marking on exit lets the same cell join several times before it is processed.
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.