Library/Coding patterns that get asked/Graphs, trees and tables

Breadth-first search on a grid

95 min7 partsCoreFundamentalsChecked Nov 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • Read a grid as a graph: four offsets and a bounds check give a cell's neighbors, and in Python a negative index wraps around without an error
  • Write breadth-first search with a deque, mark each cell when you queue it, and say what marking it when you pop it costs
  • Get the fewest steps and the number of rounds from one level-by-level loop, when every step costs the same, with -1 when something is never reached
  • Start from every source at once for spread-over-time questions, for the price of one search
  • Simulate rules a plain search can't express, like k neighbors or burnout: read each round's starting state, and touch only cells next to a change
  • Answer the follow-ups: diagonals, walls you may break, what to return when nothing reaches, and a grid too big for memory
Part 1 of 7about 12 min
A grid is a graph

Infection on a grid

OpenAI's most reported coding question is a grid simulation of an infection, from phone screens and onsites (3 reports). It starts like this:

The grid is a list of equal-length strings. . is a healthy cell and I is an infected one. Cells touch up, down, left and right.

Each day, a healthy cell becomes infected if at least k of its neighbors were infected the day before. Write days_to_infect_all(grid, k=1): the first day on which every cell is infected. Return 0 if every cell already is, and -1 if that day never comes.

GridReturns
["I.", ".."]2
["I..", "...", "..."]4
["II", "II"]0
["..."]-1, because nothing is infected, so nothing spreads

Candidates describe five parts in 60 minutes, each adding a rule, and most get through three or four (2 reports). After this one come immune cells, then recovery after a countdown, then deaths, and last, burning one whole row or column to stop the spread.

Under the story it's breadth-first search: each day the infection spreads one ring outward, from every infected cell at once. You don't write it yet. It needs two ideas first: the grid as a graph, and the search itself. At the end you solve the whole problem, level by level, in an interview simulation with a 60-minute timer.

This lesson builds on hash maps and queues: the search keeps a set of the cells it has seen and a queue of the cells to visit next. The same breadth-first search runs the web crawler in the coding builds, where small systems grow in levels, over links instead of grid cells.

A grid is a graph

The infection moves from a cell to the cells that share a side with it. So the first tool lists a cell's neighbors:

# up, down, left, right
SIDES = ((-1, 0), (1, 0), (0, -1), (0, 1))


def neighbors(grid, r, c):
    found = []
    for dr, dc in SIDES:
        nr, nc = r + dr, c + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]):
            found.append((nr, nc))
    return found


grid = ["....",
        "....",
        "...."]
for cell in [(0, 0), (0, 1), (1, 1), (2, 3)]:
    print(cell, neighbors(grid, *cell))
Predict

On an open 3 by 4 grid, how many neighbors does the corner (0, 0) have?

Pick one to see what it prints.
Pick an answer above to see the rest

A cell has at most four edges, so a search that touches each cell and edge once is O(RC)

You never build an edge list. Four offsets and a bounds check produce a cell's edges when you ask for them. Here are all the edges of that 3 by 4 grid:

Predict

A 3 by 4 grid. How many edges join two cells that share a side?

Pick an answer above to see the rest

In Python a negative index reads the far side of the grid, so check both bounds

Before the search itself, one Python trap in reading a cell's neighbors.

grid = ["....",
        "####",
        "F..."]
r = 0
print(grid[r - 1])
F...

For a cell in the top row, the row above is row -1. Python doesn't raise an error for it. It counts a negative index from the end, so grid[-1] is the bottom row:

What a top-row cell sees when it looks up
grid
row -1F...row 0....row 1####row 2F...

Row -1 isn't a real row: Python reads row 2 there, so a cell in row 0 looks up and finds a fire.

That's why the bounds check is the line that's easy to get half right. Check both ends: 0 <= nr < len(grid) and 0 <= nc < len(grid[0]).

In the editor, write open_neighbors(grid, r, c): neighbors from the top of this part, with both bounds checked and rocks # left out. Every search below calls it.

CheckpointFour sides, inside the grid, not a wall

Write open_neighbors(grid, r, c): the cells that share a side with (r, c), lie inside the grid and aren't a wall #, as a list of (row, column) tuples in any order.

Watch · 8 min

Greg Hogg on three ways to store a graph: an edge list, an adjacency matrix and an adjacency list. A grid is a graph whose edges you compute instead of store.

Graphs: Edge List, Adjacency Matrix, Adjacency List, DFS, BFS - DSA Course in Python Lecture 11 · Greg Hogg · Jul 2024YouTube
Part 1 done
Part 2 of 7about 15 min
Breadth-first search

Breadth-first search reaches cells in rings

The infection reaches the cells one step from a sick cell on day 1, the cells two steps away on day 2, and so on. A search that reaches cells in that order is breadth-first search.

BFS keeps a queue of cells to expand and a seen-set of every cell it has queued

The search keeps two things:

  • a queue of cells found but not yet expanded, taken oldest first.
  • a seen-set of every cell that has ever gone on the queue. It's the seen-set from the hash-maps lesson.

Each turn pops the oldest cell from the queue. Every open neighbor that isn't in the seen-set yet goes into the set and onto the back of the queue, both at once, so no cell is queued twice.

Here it is on a yard, YARD = ["...#.", ".#.#.", "...#."], from the top-left corner. YARD is 3 by 5: a 3 by 3 yard with a rock in the middle, then a column of rock that fences off a strip of three cells on the right. A level is the cells a fixed number of steps from the start.

Predict

The rock sits at (1,1). How many steps is (2,2), below and right of it, from (0,0)?

Pick an answer above to see the rest

Use a deque, because a list's pop(0) shifts every item behind it

The search takes cells from the front of its queue. A list is the wrong tool for that.

Taking the first item out
list.pop(0)
abcde
deque.popleft()
abcde

Red leaves. In the list, the 4 orange items behind it each move one place. In the deque, nothing else moves.

A Python list keeps its items side by side, so taking the first one shifts every other item down one place. The Python tutorial says so: pops from the front of a list are slow. collections.deque, a double-ended queue, is built for both ends, with about the same O(1) cost for an append or a pop on either side.

Drain one of each:

import time
from collections import deque

n = 200_000
as_list, as_deque = list(range(n)), deque(range(n))

start = time.perf_counter()
while as_list:
    as_list.pop(0)
print(f"list.pop(0):     {time.perf_counter() - start:.2f} s")

start = time.perf_counter()
while as_deque:
    as_deque.popleft()
print(f"deque.popleft(): {time.perf_counter() - start:.4f} s")
Predict

Draining 200,000 items with list.pop(0) took about 3.2 s. About how long for 100,000?

Pick an answer above to see the rest

Mark a cell when you queue it, and it goes on the queue only once

Here is the same search on an open 2 by 2 grid, twice. On the left, a cell is marked when it's queued, as in reachable. On the right, it's marked only when it's popped.

PopQueue after, marked when queuedQueue after, marked when popped
(0,0)(1,0) (0,1)(1,0) (0,1)
(1,0)(0,1) (1,1)(0,1) (1,1)
(0,1)(1,1)(1,1) (1,1)
(1,1)empty: 4 pops(1,1)
(1,1) againempty: 5 pops

When (0,1) pops, (1,1) is already waiting in the queue. On the left, (1,0) marked it when it queued it, so (0,1) skips it. On the right, nothing has marked it yet, so (0,1) queues it a second time. A cell gets queued once by every neighbor that pops before it does.

In the editor, write the loop in pops(grid, start, when_popped). It runs the search under either rule and returns how many entries come off the queue: 4 and 5 on the 2 by 2 grid.

Marked when popped, the copies multiply

Each extra copy of a cell, when it's popped, queues that cell's neighbors again, so the copies multiply. On an open grid searched from a corner, every cell comes off the queue once for each shortest route to it:

Copies of each cell that come off the queue, marked when popped, on an open 4 by 4 grid
pops
1111123413610141020

69 pops for 16 cells. The far corner comes off the queue 20 times.

Each number is the one above it plus the one to its left, because a shortest route from the corner only goes down and right. The totals grow fast:

GridPops, marked when queuedPops, marked when popped
4 by 41669
6 by 636923
8 by 86412,869
10 by 10100184,755
12 by 121442,704,155

The 12 by 12 row took 1.8 s, and at its peak the queue held 705,432 entries for 144 cells. For an n by n grid, each count is (2nn)−1\binom{2n}{n} - 1, 2n choose n minus 1: the number of down-and-right routes, summed over every cell. For a 20 by 20 grid that's 137,846,528,819.

The half fix is to skip a popped cell that's already marked. Then each cell is expanded once again, but the copies still pass through the queue: 265 pops for the 144 cells of the 12 by 12 grid. Marking at queue time costs nothing and keeps one entry per cell. Sedgewick and Wayne's Algorithms textbook marks each vertex in the same step that puts it on the queue.

With the mark at queue time, each cell goes on the queue at most once. Each of its at most four edges is looked at once, when it pops. That's O(RC)O(RC) time, and O(RC)O(RC) memory for the seen-set and the queue.

In the editor, finish steps_from(grid, start): a dict from each reachable cell to its number of steps from start. The dict steps is the seen-set too, so a cell gets its count in the same step that queues it.

CheckpointFewest steps to every cell

Finish steps_from(grid, start): a dict from every cell reachable from start to its number of steps from start. Walls and cells walled off stay out of the dict. steps doubles as the seen-set, so give a cell its count in the same step that queues it. Use open_neighbors, once for each cell you pop.

Watch · 3 min

Greg Hogg runs breadth-first search with a queue: the start node's neighbors first, then their neighbors.

Graphs: Edge List, Adjacency Matrix, Adjacency List, DFS, BFS - DSA Course in Python Lecture 11 · Greg Hogg · Jul 2024YouTube
Part 2 done
Part 3 of 7about 15 min
Fewest steps

BFS finds the fewest steps when every step costs the same

When every step costs one, the first count BFS gives a cell is its fewest steps

Here is the queue of the yard search after every pop, with each cell's level next to it:

Predict

Watch the queue during the search on YARD. How many different levels can sit in it at once?

Pick an answer above to see the rest
Predict

MAZE is ["..#...", "..#.#.", "....#."]. How many steps from (0,0) to (0,3), just past the wall in column 2?

Pick an answer above to see the rest

Pop from the newest end and the search goes deep, so a first count can be too long

On an open 3 by 4 grid from (0, 0):

Predict

Swap popleft() for pop(), so the newest cell comes out first. What count does (2,0), two steps below the start, get?

Pick an answer above to see the rest

Go one level per pass when you only need the number of rounds

Some questions ask only how many rounds the search takes, not the distance to each cell. Then you can handle one whole level at a time.

def fewest_steps(grid, start, goal):
    seen, queue, steps = {start}, deque([start]), 0
    while queue:
        # exactly the cells on this level
        for _ in range(len(queue)):
            r, c = queue.popleft()
            if (r, c) == goal:
                return steps
            for cell in open_neighbors(grid, r, c):
                if cell not in seen:
                    seen.add(cell)
                    queue.append(cell)
        steps += 1
    # the queue ran out: unreachable
    return -1

range(len(queue)) is worked out once, before the pass starts. So the cells appended during a pass wait for the next one:

The pass for level 2 on YARDThe queue
before the pass(2,0) (0,2): len(queue) is 2, so it pops 2
after the pass(2,1) (1,2): level 3, queued during the pass, waits for the next one

Often you need only the number of rounds: minutes for a fire, days for an infection. Then you don't need a count per cell, and this loop keeps one integer in place of the dict. It's the same O(RC)O(RC) search.

On the maze, fewest_steps(MAZE, (0, 0), (0, 3)) is 7, and the corner (2, 5) is 11. On ["..#.", "..#.", "..#."], a column of rock cuts the grid in two, and (0, 0) to (0, 3) returns -1.

In the editor, write level_sizes(grid, start) with that loop: how many cells sit on each level. On YARD, check it against the table of levels in part 2.

Count a minute only if its pass found something, then check that everything was reached

The infection question counts minutes, and an off-by-one is easy here.

A row of five trees, lit at the left end
forest
minute 0F....minute 1FF...minute 2FFF..minute 3FFFF.minute 4FFFFF

Each pass finds one new tree, until minute 4's pass finds nothing: there is no minute 5.

When the question is how long until everything is reached, two details decide whether the count is right:

  • Count a round only if it reached something. The pass over the last level finds nothing new. Counting it is off by one.
  • Check that everything was reached. An empty queue means the search is over, not that it covered the grid, as the yard's fenced-off strip showed. Compare what you reached with what had to be reached.

In the editor, finish minutes_from(grid, start) with both rules: the minutes until every tree burns from one fire at start, or -1 if some tree never catches. trees counts the trees to reach.

CheckpointCount the minutes, and say never

A fire starts on the tree at start at minute 0, and each minute it spreads to every tree beside a burning one. Finish minutes_from(grid, start): the minutes until every tree . is burning, or -1 if some tree never catches. Rocks # never burn. Go one level per pass.

Part 3 done
Part 4 of 7about 8 min
Many sources

Start from every source at once

Put every source on the queue at step 0, and each count is the fewest steps to the nearest one

Spread questions start from many places at once: several fires, every rotten orange, all the infected cells on day 0. It takes one change to steps_from:

def steps_to_nearest(grid, sources):
    steps = {cell: 0 for cell in sources}
    queue = deque(sources)
    while queue:
        r, c = queue.popleft()
        for cell in open_neighbors(grid, r, c):
            if cell not in steps:
                steps[cell] = steps[r, c] + 1
                queue.append(cell)
    return steps

Every source goes on the queue at step 0, before the first pop. Here are two fires at the ends of a row:

Two fires at the ends of a row
minute
0F.....F1FF...FF2FFF.FFF3FFFFFFF

Minute 0's queue holds both fires. They spread in the same minutes and meet at (0,3), the last cell queued.

Both fires are level 0, so they spread in the same minutes and meet in the middle at minute 3.

A tree catches when the nearest fire reaches it. So you want each cell's distance to its nearest source, and the answer is the largest of those. Picture one extra cell joined to every source by an edge. BFS from that cell would pop it, queue all the sources, and carry on exactly like this. So everything above about BFS holds, and each count is the fewest steps from the nearest source.

Here it is on a forest with two fires and a wall of rock:

Predict

Fires at (0,0) and (2,5) in ["F.....", "..#...", "..#..F", "......"]. What count does (0,4) get?

Pick an answer above to see the rest

One search from every source at once costs O(RC), whatever the number of sources

The other way to get this map runs one BFS per source and keeps the smaller count for each cell. It gives the same answer at SS times the cost for SS sources. On an open 200 by 200 grid, 40,000 cells, with sources at random spots:

SourcesOne search per sourceOne search from all
140,000 pops, 0.032 s40,000 pops, 0.033 s
10400,000 pops, 0.336 s40,000 pops, 0.032 s
502,000,000 pops, 1.659 s40,000 pops, 0.030 s

Both methods produced the same map in every row. From all sources at once it's O(RC)O(RC), whatever SS is.

In the NeetCode video at the end of this part, he counts fresh oranges down as they rot, and anything left at the end means -1. That's the same check as comparing the cells you reached with the cells that had to be reached, done with a counter.

In the editor, minutes_to_burn(grid) finds every fire F and counts the trees. Fill in its two missing lines: seed seen and queue with every fire, and return the answer.

CheckpointEvery fire at minute 0

The grid now marks its fires: every F is burning at minute 0. Fill in the two missing lines of minutes_to_burn(grid): seed the search, and return the minutes until every tree burns, 0 if no tree is left to burn, or -1 if some tree never catches.

Watch · 4 min

NeetCode draws the multi-source search on the rotting-oranges grid. Why a search from one rotten orange gets the time wrong, the queue seeded with every rotten orange, one minute per level, and a count of fresh oranges to tell when the answer is -1.

Rotting Oranges - Leetcode 994 - Python · NeetCode · Nov 2021YouTube
Part 4 done
Part 5 of 7about 15 min
Rounds

Simulate in rounds when the rule goes beyond distance

When a tree needs k burning neighbors, the minute it catches is no longer its distance

Here's a forest where a tree catches only when at least k = 2 of its neighbors are burning:

k = 2: a tree catches when two neighbors burn
minute 0
F.F...F..
minute 1
FFFF..F..
minute 2
FFFFF.F..
minute 3
FFFFFFFF.
minute 4
FFFFFFFFF

The bottom-right tree is 2 steps from the nearest fire. It catches at minute 4, once two of its neighbors are burning. A BFS would say 2.

BFS fits when one burning neighbor is enough and a fire burns forever. Interview spreads add rules: a tree catches only when at least k of its neighbors burn, a fire burns out, an infected cell recovers. Then the minute a cell catches is no longer its distance from a source.

In the editor, write burning_neighbors(grid, r, c), how many of a cell's neighbors are F. Then write catches(grid, r, c, k), whether a tree catches this minute. K2 is the k = 2 forest above.

Read the old grid and write a new one, so all of a minute's changes land at once

So you simulate: work out each round's grid from the one before. One rule keeps it right. Every cell reads the grid as it was at the start of the round, and every change lands at once. Read from the old grid and write into a new one:

def spread_once(grid, k=1):
    # write here
    new = [list(row) for row in grid]
    # read here
    for r, row in enumerate(grid):
        for c, state in enumerate(row):
            if state == ".":
                burning = sum(grid[nr][nc] == "F" for nr, nc in open_neighbors(grid, r, c))
                if burning >= k:
                    new[r][c] = "F"
    return ["".join(row) for row in new]


def minutes_by_rescan(grid, k=1):
    minutes = 0
    while True:
        new = spread_once(grid, k)
        # a round that changes nothing ends it
        if new == grid:
            break
        grid, minutes = new, minutes + 1
    return -1 if any("." in row for row in grid) else minutes

Strings can't be changed in place, so [list(row) for row in grid] makes each row a list of characters, and "".join(row) turns it back into a string. The sum counts the burning neighbors: each comparison is True or False, and True adds as 1. On the k = 2 forest above, minutes_by_rescan returns 4.

Here's what the new grid buys, on the one-row forest F.... with k = 1:

F.... with k = 1, two ways
a new grid each minute
minute 1FF...minute 2FFF..minute 3FFFF.minute 4FFFFF
written in place
minute 1FFFFF

Scanning left to right in place, each new fire lights the next tree in the same minute. Red trees caught too soon.

In the editor is spread_once with one wrong read, and it lights the whole row F.... in one minute. Find it and fix it.

A fire that goes out this minute still lights its neighbors this minute

So far a fire burned forever. Now it burns for one minute.

A fire burns for one minute, then turns to ash, A
row
minute 0F..minute 1AF.minute 2AAFminute 3AAA

At minute 1, (0,0) goes out, and in the same minute it lights (0,1).

Real rules change more than one thing per round: a fire that burns for one minute and then turns to ash, A, or an infected cell that recovers. Reading the old grid handles both in the same pass. A fire that goes out this minute was still burning at the start of the minute, so it still lights its neighbors this minute. Write the order of events down before you code it, because that's where a wrong order or an in-place write hides.

When a fire burns for bb minutes instead of one, you know the minute it goes out the moment it catches: that minute plus bb. Keep a schedule, a defaultdict(list) from a minute to the cells that go out then. Add a cell when it catches (ends[minute + b].append(cell)). At each minute, apply ends.pop(minute, []) together with that minute's new fires. Here is F.. with b=3b = 3:

A fire that burns for b = 3 minutes
row
minute 0F..minute 1FF.minute 2FFFminute 3AFFminute 4AAFminute 5AAA

(0,0), (0,1) and (0,2) catch at minutes 0, 1 and 2, and go out at 3, 4 and 5.

In the editor, write the loop in burn_once(grid, k): one minute of a forest where fires burn out. Every fire F turns to ash A, and every tree with at least k burning neighbors at the start of the minute catches.

CheckpointOne minute, two kinds of change

Fires now burn out. Write the loop in burn_once(grid, k), one minute of the forest: every fire F turns to ash A, and every tree . with at least k burning neighbors at the start of the minute catches. Ash and rocks # never burn.

When fires never go out, only trees next to last minute's new fires can catch

The rescan is correct, but on a big forest it's slow. When fires never go out, there's a faster way.

A 5 by 5 forest lit at (0,0), at the start of minute 3
forest
FF*?.F*?..*?...?.........

F caught at minute 0 or 1. * caught at minute 2: the frontier. ? are the only trees that can catch at minute 3. A rescan reads every . too, and nothing changes there.

A rescan reads every cell every round, O(RC)O(RC) per round, and a spread can take many rounds. On a 60 by 60 forest with one fire in a corner, the fire needs 118 minutes. The rescan makes 119 passes, the last one changing nothing, so it reads 428,400 cells: 0.169 s here, the middle of five runs.

Most of those reads can't change anything. When fires never go out, a tree can only catch in a minute if one of its neighbors caught the minute before. Otherwise its count of burning neighbors didn't change, and it would have caught already. So keep the cells that changed last round, called the frontier, and look only at their neighbors. The worked example below builds that, and on the same forest it took 3.0 ms.

In the editor, write candidates(grid, frontier): the trees that share a side with a cell in frontier. forest is the forest in the figure, and frontier holds the three cells that caught at minute 2.

Part 5 done
Part 6 of 7about 10 min
The worked example

A worked example: a fire that needs k neighbors

The problem: a forest of trees ., rocks # and fires F. A tree catches on a minute when at least k of its neighbors were burning the minute before, and fires never go out. Return the minutes until every tree burns, 0 if none is left to burn at the start, or -1 if some tree never catches. This is how a candidate should take it.

Say the rules back, then start from the rescan that is plainly right

1. Say the rules back. Neighbors share a side. Rocks never burn and never count. Every change in a minute reads the minute before. Then ask the questions the tests will ask:

  • No trees at all: 0.
  • No fire: -1, unless there are no trees.
  • k above 4: no tree has five neighbors, so nothing ever catches.

2. Start with the version that's plainly right. That's minutes_by_rescan: rounds that read the old grid and write a new one. State its cost, O(RC)O(RC) per minute, and offer to make it faster.

In the editor, write quick_answer(grid, k): the answer for those three cases, or None when only a simulation can tell.

Keep a heat count per tree, fed only by last minute's new fires

3. Find the waste. A tree's count of burning neighbors changes only when a neighbor catches. So keep two things:

  • fresh, the cells that caught last minute. At the start that's every fire.
  • heat, a dict from a tree to how many of its neighbors are burning so far.

Each minute, every fresh cell adds one heat to each unburnt tree beside it, and a tree whose heat reaches k catches. Collect the catches first and apply them after all the reads, so a tree that catches this minute heats nobody until the next one.

def minutes_to_burn_k(grid, k=1):
    state = [list(row) for row in grid]
    fresh = [(r, c) for r, row in enumerate(grid) for c, ch in enumerate(row) if ch == "F"]
    # tree -> burning neighbors so far
    heat = {}
    minutes = 0
    while fresh:
        catching = []
        # only last minute's new fires
        for r, c in fresh:
            for nr, nc in open_neighbors(grid, r, c):
                if state[nr][nc] == ".":
                    heat[nr, nc] = heat.get((nr, nc), 0) + 1
                    # == so each tree is added once
                    if heat[nr, nc] == k:
                        catching.append((nr, nc))
        # all at once, after the reads
        for r, c in catching:
            state[r][c] = "F"
        if catching:
            minutes += 1
        fresh = catching
    return -1 if any("." in row for row in state) else minutes

fresh is the level-by-level loop again, with the catches standing in for the next level. Here is each pass on the k = 2 forest, ["F.F", "...", "F.."], after the fresh fires have added their heat:

Each pass on the k = 2 forest, after the fresh fires add their heat
pass 1
*2*2.1*1.
pass 2
F*F*21F1.
pass 3
FFFF*2F2.
pass 4
FFFFF*F*2
pass 5
FFFFFFFF*

* is fresh, caught the minute before. F is an older fire. A digit is an unburnt tree's heat. Catches: (0,1) and (1,0), then (1,1), then (2,1) and (1,2), then (2,2), then nothing.

A tree catches on the pass its heat reaches 2. Heat stays between passes: (1,2) gets 1 on pass 1 and its second on pass 3. On pass 5, (2,2) is the only fresh cell, it has no unburnt neighbor, nothing catches, and the loop ends. Four passes caught something, every tree is burning, so the answer is 4, the same as the rescan.

In the editor is minutes_to_burn_k with one bug, and it says -1 for the k = 2 forest. Find the bug and fix it.

Test the edges, then check the fast version against the slow one

Before you call the spread done, test it the way the interviewer will.

Predict

The forest is ["FF", "F#"]: three fires and a rock. What should minutes_to_burn_k return?

Pick an answer above to see the rest
Part 6 done
Part 7 of 7about 20 min
Follow-ups

What interviewers ask next

Once the levels pass, expect the interviewer to change the rules of the grid. Here are the usual follow-ups, one at a time, starting with diagonals.

What about diagonals? Use eight offsets, and the distances shrink

The neighbors, o, of a cell, X
four offsets
.o.oXo.o.
eight offsets
ooooXoooo
eight, on two rocks
X##o

With eight offsets, X reaches o in one diagonal step, between two rocks that touch.

Use eight offsets instead of four. Distances shrink: corner to corner on a 10 by 10 grid is 18 steps with four neighbors and 9 with eight. Ask whether a diagonal step may squeeze between two walls that touch at a corner. With plain eight neighbors it can: on [".#", "#."], (0, 0) reaches (1, 1) in one step.

The code doesn't change. The facts that counted four sides do:

  • The worked example's never case becomes k above 8.
  • A tree's heat can go up eight times.
  • Marking a cell when it's popped now writes wrong counts, on top of the extra pops. A neighbor on the cell's own level can queue it again, with a count one too high.

In the editor, fill in EIGHT and write neighbors8(grid, r, c, squeeze). When squeeze is False, a diagonal step may not pass between two rocks that touch at a corner.

What if you may break one wall? Search over the cell plus the walls broken so far

A classic follow-up: the fewest steps when you may knock down one wall.

Predict

You may break one rock on MAZE. How many steps from (0,0) to (0,3) now?

Pick an answer above to see the rest

What do you return when nothing reaches a cell? Agree on it before you code

-1 is the usual answer for a count. For a map of distances, leave the cell out or give it math.inf, and say which. Keep 0 and -1 apart: 0 means done at the start, -1 means never. Test both, plus a grid with no source at all.

How do you get the path, not just its length? Store each cell's parent

Store parent[cell] = (r, c) in the same step that marks a cell. Then walk back from the goal to the start, and reverse. It's one more dict, still O(RC)O(RC). On the maze, the walk back from the corner gives this 11-step path:

The path read from the parents, from (0,0) to G
path
↓.#→→↓↓.#↑#↓→→→↑#G

Each arrow points to the next cell. G is the goal, (2,5).

In the editor, finish path_to(grid, start, goal): store each cell's parent as you queue it, then walk back from goal. Return None when nothing reaches the goal.

What if the grid is too big for memory? Shrink the seen-set first

Another follow-up is about scale: a grid too big to hold in memory.

A 2 by 3 grid in one bytearray, with C = 3
grid
row 0012row 1345
bytearray
012345

Cell (r, c) is at index r * C + c.

Predict

On an open 1,000 by 1,000 grid, a seen-set of (r, c) tuples peaked at 137 MB. About how much does a bytearray with one byte per cell take?

Pick an answer above to see the rest

Why not a recursive fill? It can go one call deep per cell, past Python's default limit of 1,000

You may be asked why you didn't write the search as a recursion. It's shorter, but it has a limit.

Predict

A recursive fill goes one call deep per cell. On an open square grid, what's the largest that fits under Python's default limit of 1,000?

Pick an answer above to see the rest

What tests would you write? The edges, a grid that isn't square, and the same grid flipped

  • A 1 by 1 grid.
  • A grid of only walls.
  • A cell walled off: -1.
  • Everything already done: 0.
  • k above 4.
  • A grid that isn't square. It catches swapped rows and columns.
  • The same grid flipped. It catches an in-place update.

The last test on that list turns the grid around. In the editor, write turn(grid), which turns a grid 180 degrees, and same_when_turned(minutes, grid, k), which checks that a minutes function gives the same answer both ways.

What about the practice problem's fifth part? Say the R + C bound first

Burn one whole row or column to stop the spread, and choose the one that leaves the fewest dead. There are R+CR + C choices, each a full simulation, so it costs R+CR + C times one simulation. Say that bound first, then look for ways to skip choices.

The practice problem, start to finish

That's every piece the practice problem needs. It asks for every level from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
6 questions
  1. 1.You run BFS from one cell of a grid where every move is one step. The first time the search reaches a cell, what do you know?

  2. 2.You mark cells as seen when you pop them, not when you queue them, and you don't skip repeats. On an open 10 by 10 grid searched from a corner, how many entries come off the queue?

  3. 3.Fifty fires on an open 200 by 200 grid. You want the minute each tree catches. What does one search from every fire at once cost, against one search per fire?

  4. 4.A one-row forest F...., a fire on the left and four trees, one burning neighbor is enough. You update the grid in place, scanning left to right. What does your code report?

  5. 5.Your level-by-level loop adds a minute after every pass, including the pass that finds nothing new. What does it return for a row of five trees lit at one end?

  6. 6.In the forest F.F / ... / F.., a tree needs two burning neighbors to catch. The bottom-right tree is two steps from the nearest fire. When does it catch?

Where this shows up

The reports behind this lesson, each with its source.

Hello Interview lists 'Web Crawler Multithreaded' (BFS crawl from a seed URL) with Anthropic Senior reports in its timeline (early December 2025, late May 2026).

Prep site·Hello Interview (prep site; candidate timeline)Source

Practice

Sources (5)
  1. 4.1 Undirected Graphs · Algorithms, 4th Edition (Sedgewick and Wayne), booksite · Apr 16, 2019
    “For any vertex v reachable from s, BFS computes a shortest path from s to v (no path from s to v has fewer edges). BFS takes time proportional to V + E in the worst case.”
  2. collections: deque objects · Python 3.12 documentation · Oct 26, 2026
    “Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction.”
  3. Data Structures: Using Lists as Queues · Python 3.12 documentation · Oct 26, 2026
    “While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).”
  4. Built-in Types: Common Sequence Operations · Python 3.12 documentation · Oct 26, 2026
    “If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted.”
  5. sys.getrecursionlimit · Python 3.12 documentation · Oct 26, 2026
    “This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.”