6/32
Part 2 of 7 · Breadth-first searchLearn and do

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