← Visualizers
Graphs · Multi-source BFS LeetCode 1162

As Far from Land as Possible / visualized

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.

Execution

idle
INVARIANT Wave Depth Invariant: Answer is the depth of the LAST BFS wave, not individual cell values. We initialize dist = -1 because land cells occupy level 0. Boundary guard: return -1 if q.isEmpty() (all water) or q.size() == m*n (all land).
Press Run to begin.
0 / 0
Speed

Java · running line

popping now reached — level drawn for you, never stored land, seeded at level 0 deepest water — the answer water not reached yet
INTERVIEW SCRIPT

How to Explain As Far from Land as Possible to an Interviewer

1. Multi-Source BFS from All Land

"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)$."

2. Why 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."

3. The -1 Edge Guards

"If q.isEmpty() (all water) or q.size() == m * n (all land), no water-land pair exists. Both edge cases must return -1."

4. Contrast with LC 542

"LC 542 returns the full 2D distance matrix. LC 1162 returns only the maximum distance reached by the final BFS wave."

O(m·n) time and space  ·  the level numbers on the board are drawn for the reader — the program stores none of them. It keeps one 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.