Number of Enclaves

medium

Given an R × C grid of 0s (sea) and 1s (land), a move steps 4-directionally between land cells, and you may walk off the grid only from a boundary cell. Return the number of land cells from which it is impossible to walk off the boundary — the enclaves.

Hints

A land cell escapes only if it connects (through land) to a boundary cell.
Instead of testing each cell, flood inward from every boundary land cell.
The land that survives the flood is enclosed — count it.

Common doubts

Testing each cell reruns a flood per cell — O((R·C)²). One flood from all boundary sources removes every escapable cell in O(R·C).
Every boundary land cell is an equally valid escape point, so they all seed the same flood simultaneously.
Same border-flood idea: mark what the boundary reaches, then act on the rest.

Interview follow-ups

After the flood, collect the coordinates of surviving land.
Add the four diagonals; more land becomes border-connected, so fewer enclaves.

Fun facts

  • LeetCode 1020 — the 'walk off the boundary' framing of the border-flood pattern.
  • The same inward flood underlies surrounded regions and the pacific-atlantic water flow.

Asked at

AmazonGoogle
Frequently Sometimes Occasionally
Example 1
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,1]]
Output: 3
The inner block of land can't reach the border; the border-touching land can.
Example 2
Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 1
The single central land cell is fully enclosed.
Constraints

- 1 <= R, C <= 500 - grid[i][j] is 0 or 1

Solve this problem →