A BFS level is a distance. Eight directions, a size snapshot taken before each level, and the one line the whole pattern rests on: mark on push, in the same statement that enqueues. Flip the toggle to run the mark-on-pop version and watch the queue.
sz = q.size() ensures all distance-d cells are processed before any distance-(d+1).
"Since all 8 directional moves have equal unit weight of 1, BFS is guaranteed to discover the target node in the minimum number of steps."
"We MUST mark seen[nr][nc] = true at the exact moment of enqueuing. If you mark on pop, multiple active wavefront cells enqueue the same neighbor, blowing up the queue exponentially and corrupting shortest path distances!"
sz = q.size()"Taking a snapshot of the queue size guarantees that all nodes at distance $d$ are exhausted before any node at distance $d+1$ is polled."
"Each grid cell is pushed to the queue at most once. Time is $O(n^2)$ and auxiliary space is $O(n^2)$ queue memory."
too large — failure mode 1.1, a distance greater than the true minimum.