← Visualizers
Graphs · Boundary seeding — invert the question LeetCode 1020

Number of Enclaves / visualized

You cannot mark enclosed directly — proving a cell never reaches the edge means exploring everywhere it could go. So invert it: seed a flood from every land cell on the border, sink everything it touches, and the land still standing is exactly the land that could not walk off the board.

Execution

idle
INVARIANT Boundary Seeding Invariant: Don't search for enclaves from the inside. Invert the problem: sink all land connected to the outer boundary first. Any land cell still standing (1) is guaranteed to be an enclave!
Call Stack · Border Flood Traversal Top = Active · Bottom = Suspended Parents
Press Run to begin.
0 / 0
Speed

Java · running line

border seed sinking now on call stack enclave — counted escaped off edge water
INTERVIEW SCRIPT

How to Explain Number of Enclaves to an Interviewer

1. Invert the Question

"Searching from the interior to see if an island leaks requires complex state tracking. Instead, invert the perspective: all boundary cells and their connected components can escape off-grid."

2. Border Flood & Sinking

"Loop over the 4 grid borders. Whenever grid[r][c] == 1, launch DFS and sink every reachable cell to 0 before recursing. This neutralizes all escaping components."

3. The Complement Counting Trick

"After border flooding, any cell still reading 1 is an enclave by construction! A simple nested loop summing count += grid[r][c] gives the final answer."

4. The LC 130 Equivalence

"Point out that LC 1020 is identical to LC 130 (Surrounded Regions): LC 130 flips the surviving cells to 'X', while LC 1020 sums them. Time is $O(m \cdot n)$ and auxiliary space is $O(m \cdot n)$ stack depth."

O(m·n) time · O(m·n) worst-case recursion depth  ·  the border flood is the algorithm, and it is byte-for-byte the flood in LC 130. Sinking a border-reachable cell is not destruction — it is the mark, and count += grid[r][c] then reads the complement for free.