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

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.