Two things hold on every line:
- The queue holds at most two levels, and they're neighbors: some level d and level d+1.
- The nearer level is in front.
That's no accident. The queue starts with level 0, the start alone. Popping a level-d cell only queues level-d+1 cells, and they go in at the back. So the queue hands out cells in order of level.
Now take a cell X, first found from a cell P on level d, so X gets d+1. If X were really closer, it would have a neighbor on a level below d. That neighbor would have left the queue before P, and it would have found X first. So the first discovery is the shortest, and the count is final the moment it's written. (2,2) can be reached around either side of the rock, but it is queued once. In the trace, it's found first from (2,1), at level 4. When (1,2) pops, (2,2) is already in seen, and its count stays 4.
Sedgewick and Wayne's Algorithms textbook states this as a proposition: for every vertex reachable from the start, BFS finds a path with the fewest edges, in time proportional to V+E in the worst case.
That rests on every step costing the same. BFS counts steps. When steps can cost different amounts, the route with the fewest steps need not be the cheapest one.
Here are the counts on a maze, MAZE = ["..#...", "..#.#.", "....#."], from the top-left corner: