Number of Enclaves

Medium

Topics
GraphDFSBFSUnion FindMatrix

Given a binary grid where 1 is land and 0 is sea, return the number of land cells from which you cannot walk off the boundary of the grid moving 4-directionally through land.

Example 1

000001101020110300000123
cannot reach the border — countedcan walk off the grid
Walk only between land cells that share a side. Any land connected to the border can escape, so it does not count. The answer is the number of land cells that cannot reach the border — 3.
2D grid — one row per line.
Input:  grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3

Example 2

001101001020010300000123
can walk off the grid
Input:  grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0

Constraints

  • 1 <= m, n <= 500
  • grid[i][j] is 0 or 1.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Asking which land cells cannot reach the border means tracking reachability for every cell. Invert it: flood inward from every border land cell, sinking everything the walk reaches. Whatever land survives is, by construction, unable to reach the border. One flood instead of one per cell.

The shown solution uses an explicit stack rather than recursion, and here the difference is stark. At the stated limit of 500×500 an all-land grid is one component of 250,000 cells. The recursive version raises RecursionError in Python even with the limit lifted to 100,000 the way the site's judge does, throws StackOverflowError in Java, and crashes Node. Three of the four languages fail on an input the problem explicitly permits.

Approach

  1. Seed a stack with every land cell on the four borders, sinking each as it is pushed.
  2. While the stack is non-empty, pop a cell and push its unvisited land neighbours, sinking each at push time.
  3. Count the land cells that remain.

Dry Run

grid  (1 is land, 0 is sea)

  0 0 0 0
  1 0 1 0
  0 1 1 0
  0 0 0 0

border land: (1,0) -- sunk, and it has no land neighbours
remaining land: (1,2), (2,1), (2,2) -- connected to each other, none on a border

answer 3

Complexity

  • Time — O(m·n): each cell is sunk at most once and examined a constant number of times, plus one final counting pass.
  • Space — O(m·n) for the stack when the grid is one large component. The grid doubles as the visited marker.

Common Pitfalls

  • Writing it recursively. Measured above: it fails in Python, Java and Node at the stated 500×500 bound. This is the one genuine trap in an otherwise routine flood fill.
  • Seeding only the corners, or only the rows and not the columns. Every border cell is an escape route.
  • Double-seeding when the grid has a single row or column, where the first and last cell of a row are the same cell. Sinking at seed time makes the second attempt a harmless no-op; a version that sinks later pushes it twice.
  • Counting the survivors before the flood has drained.
  • Sinking on pop instead of on push, which lets a cell enter the stack through each of its neighbours.
  • Solving it the direct way — a separate search from every interior land cell asking whether it can escape. That is O((m·n)²) without memoisation, and the single inward flood makes it unnecessary.

Full Solution — all languages

class Solution:
    def numEnclaves(self, grid):
        R, C = len(grid), len(grid[0])
        # Explicit stack, not recursion. A 500x500 all-land grid is one component
        # 250,000 cells deep, which overflows the call stack in every language.
        stack = []

        def seed(r, c):
            if grid[r][c] == 1:
                grid[r][c] = 0
                stack.append((r, c))

        for r in range(R):
            seed(r, 0)
            seed(r, C - 1)
        for c in range(C):
            seed(0, c)
            seed(R - 1, c)
        while stack:
            r, c = stack.pop()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == 1:
                    grid[nr][nc] = 0   # sink on push, never on pop
                    stack.append((nr, nc))
        return sum(row.count(1) for row in grid)
SensAI
Beta
Tap the mic to stop voice mode