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

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.