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.
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.
Input: grid = [[0,0,0],[0,1,0],[0,0,0]] Output: 1 The single central land cell is fully enclosed.
- 1 <= R, C <= 500 - grid[i][j] is 0 or 1
A land cell can escape the grid iff it's connected (through land) to a boundary land cell. So the enclaves are all land minus the land reachable from the border. Instead of testing each cell, flood inward from the boundary: seed every boundary land cell and sink everything reachable. Whatever land survives is enclosed.
This "start from the edge" inversion is a recurring grid trick (it also solves surrounded regions and pacific-atlantic). Multi-source BFS seeds all boundary cells into one queue at once. O(R·C).
“When can a cell escape?”
Only if connected via land to a boundary land cell.
“4- or 8-directional?”
4-directional.
Land escapes only if it reaches the border, so I flood inward from every boundary land cell and sink it.
The land left standing can't reach the border — that's the enclave count. O(R·C).
Worked example — grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
no boundary land is set here -> flood removes nothing on the border
the inner block {(1,2),(2,1),(2,2)} and (1,0)... (1,0) is on the border column? col 0 is boundary -> escapes
enclosed land = {(1,2),(2,1),(2,2)} = 3
A cell is an enclave exactly when it can't reach a border land cell.
One inward flood removes all escapable land.
Count the 1s left after the flood.
| Boundary DFS | Multi-source BFS | |
|---|---|---|
| Seeds | recurse from each boundary land cell | all boundary land in one queue |
| Time | O(R·C) | O(R·C) |
| Risk | deep recursion | none |
Both remove border-connected land and count the rest. Full code is in the Approaches selector below.
Key takeaway
Flood inward from every boundary land cell and sink it; the land that survives can't escape — that's the enclave count. O(R·C).
seed all boundary land into the flood; sink reachable land answer = remaining 1s