LeetCode #1020 Medium

Number of Enclaves

Number of Enclaves is LeetCode 1020 (Medium). You get an m × n grid where 0 is sea and 1 is land.

  • One move goes from a land cell to the land cell directly above, below, left or right of it, or walks off the grid from a land cell on the border.
  • Return how many land cells can never walk off the grid, however many moves they make.

The grid can have 250,000 cells, so each cell should be handled only a constant number of times.

Constraints
  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • grid[i][j] is either 0 or 1.
graphsdfsbfsmatrix
Open on LeetCode ↗
02

Intuition

A land cell can walk off exactly when a path of land joins it to some land cell on the border, since the last move from that border cell leaves the grid.

So do not ask every cell whether it can escape. Start from the border instead: sink every land cell that border land can reach, and whatever land is left is trapped. One flood started from all border cells at once touches each cell at most once, so the whole grid costs O(m × n).

How to spot this pattern

"Count or change the cells that cannot reach the edge" is a border flood fill: start from the boundary and work inward. Surrounded Regions uses the same flood and repaints the trapped cells instead of counting them.

03

Approach

Try it first

Before reading on, decide where the search should start so that each cell is visited only once, rather than once for every land cell that asks whether it can escape. Then decide how a cell is marked so it is never pushed twice.

1

Push and sink every border land cell

Scan the first and last row and the first and last column. Each land cell there escapes in one move, so set it to 0 and push it on a stack. Sinking a cell when it is pushed means it can never be pushed a second time.

2

Spread inward from the stack

Pop a cell and look at its four neighbours. Each one that is inside the grid and still land can walk to this cell and then off the grid, so sink it and push it too.

3

Count the land that is left

When the stack is empty, add up the grid. Every remaining 1 is a land cell the flood never reached, and that sum is the answer.

4

Why the leftover land is exactly the enclaves

Every sunk cell was pushed by a sunk neighbour, and that chain leads back to a border cell, so each one can escape. In the other direction, if a remaining cell had a land path to the border, the flood would have moved along that path, cell by cell, and sunk it.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numEnclaves(self, grid: list[list[int]]) -> int:
▶3 m, n = len(grid), len(grid[0])
▶4 stack = []
▶5 for r in range(m):
▶6 for c in range(n):
▶7 on_border = r in (0, m - 1) or c in (0, n - 1)
▶8 if on_border and grid[r][c] == 1:
▶9 grid[r][c] = 0
▶10 stack.append((r, c))
▶11 
▶12 while stack:
▶13 r, c = stack.pop()
▶14 for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
▶15 if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 1:
▶16 grid[nr][nc] = 0
▶17 stack.append((nr, nc))
▶18 
▶19 return sum(map(sum, grid))
01230123stack1, 0topsealandescapesrow 1, col 0 is land on the border → sink it, push
cell1, 0border land
stack1 cells
The border scan finds land at row 1, col 0. One move walks it straight off the grid (the red arrow), so it is not an enclave. Sink it now, so it is never pushed twice, and push it so its neighbours get checked.
01230123stackemptysealandescapespop row 1, col 0 → check its 4 neighbours
cell1, 0can escape
stack0 cells
Take the top cell, row 1, col 0. It can reach the edge, so any land next to it can too: step onto it, then follow the red arrows out. Check below, above, right and left, in the code's order.
01230123stackemptysealandescapesbelow is sea → skip
below2, 0sea
row 2, col 0 is sea. Moves only go between land cells, so the flood cannot spread through it.
01230123stackemptysealandescapesabove is sea → skip
above0, 0sea
row 0, col 0 is sea. Moves only go between land cells, so the flood cannot spread through it.
01230123stackemptysealandescapesright is sea → skip
right1, 1sea
row 1, col 1 is sea. Moves only go between land cells, so the flood cannot spread through it.
01230123stackemptysealandescapesleft is off the grid → skip
leftoff the grid
There is no cell left row 1, col 0; that direction leaves the grid. The bounds check skips it, since only cells inside the grid can be sunk.
01230123stackemptysealandescapestrappedstack empty → 3 land cells left: answer 3
answer3
Nothing more can be reached from the border. The 3 land cells still standing have no land path to the edge, so they are the enclaves. Summing the grid counts them.
05

Common pitfalls

Counting all land that is not on the border

✗ Wrong
return sum(grid[r][c] for r in range(1, m - 1)
           for c in range(1, n - 1))
✓ Right
flood from the border first,
then count the land left

An inner cell can still escape through a chain of land. In [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] the two inner 1s connect up to the top row, so the answer is 0, not 2.

Moving diagonally

✗ Wrong
for dr in (-1, 0, 1):
    for dc in (-1, 0, 1):
✓ Right
for nr, nc in ((r + 1, c), (r - 1, c),
               (r, c + 1), (r, c - 1)):

Moves are only up, down, left and right. In [[1,0,0],[0,1,0],[0,0,0]] the centre cell touches the corner only diagonally, so it is trapped and the answer is 1; with diagonal moves it wrongly becomes 0.

Recursive DFS on a big grid in Python

✗ Wrong
def dfs(r, c):
    ...
    dfs(r + 1, c)
✓ Right
stack = [...]
while stack:
    r, c = stack.pop()

A 500 × 500 grid that is all land, or a long winding strip of land, makes the recursion as deep as the strip, far past Python's default limit of 1,000 calls, and it raises RecursionError. The explicit stack has no depth limit.

06

Edge cases

One row or one column, like [[1, 1, 1]]

Every cell lies on the border, so all land is sunk in the first scan and the answer is 0.

07

Complexity

Time
O(m × n)
Space
O(m × n)
The border scan and the final sum each read every cell once, and each land cell is sunk and pushed at most once. The stack can hold O(m × n) cells when most of the grid is land; the grid itself serves as the visited marks.
08

Number of Enclaves FAQ

How is this different from Surrounded Regions and Number of Islands?

Surrounded Regions (130) runs the same border flood but rewrites the trapped cells instead of counting them. Number of Islands (200) counts groups of land, not cells, and does not care about the border.

DFS or BFS: which is better?

Neither. Swapping the stack for a queue turns this DFS into a BFS; cells are sunk in a different order, but the same set gets sunk, so the count is identical.

Can I avoid changing the input grid?

Yes. Keep a separate seen grid of booleans and count land cells that are not seen at the end. It costs another m × n cells of memory.