Seed every land cell before the first pop and the water fills in level by level, each cell reached at exactly its distance to the nearest land. But 1162 never asks for that field. The answer is the depth of the last level — a single counter — so the whole matrix is scaffolding that gets thrown away at return. Run the identical machine, keep the array, and you have LeetCode 542 instead; the difference between the two problems is one line.
"Searching for land from every water cell takes $O((m \cdot n)^2)$. Instead, push every land cell (1) into the queue at $t=0$ and flood into adjacent water simultaneously in $O(m \cdot n)$."
dist = -1 Initially?"The initial queue holds the land cells at distance 0. The first BFS iteration increments dist++ to 0 while popping land, so water cells reached in the subsequent wave get correct distance 1."
"If q.isEmpty() (all water) or q.size() == m * n (all land), no water-land pair exists. Both edge cases must return -1."
"LC 542 returns the full 2D distance matrix. LC 1162 returns only the maximum distance reached by the final BFS wave."
int, and because the seeding round is the land itself, that counter starts at -1, not 0. All land or all water and no water cell has any land to be far from: -1, which is the same sentinel for two opposite grids.