Number of Enclaves
Medium
Topics
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
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3
Example 2
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
- Seed a stack with every land cell on the four borders, sinking each as it is pushed.
- While the stack is non-empty, pop a cell and push its unvisited land neighbours, sinking each at push time.
- 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 3Complexity
- 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)import java.util.*;
class Solution {
private static final int[] DR = {1, -1, 0, 0};
private static final int[] DC = {0, 0, 1, -1};
public int numEnclaves(int[][] grid) {
int R = grid.length, C = grid[0].length;
// Explicit stack, not recursion. A 500x500 all-land grid is one component
// 250,000 cells deep and overflows the call stack.
int[] stack = new int[R * C];
int top = 0;
for (int r = 0; r < R; r++) {
if (grid[r][0] == 1) { grid[r][0] = 0; stack[top++] = r * C; }
if (grid[r][C - 1] == 1) { grid[r][C - 1] = 0; stack[top++] = r * C + C - 1; }
}
for (int c = 0; c < C; c++) {
if (grid[0][c] == 1) { grid[0][c] = 0; stack[top++] = c; }
if (grid[R - 1][c] == 1) { grid[R - 1][c] = 0; stack[top++] = (R - 1) * C + c; }
}
while (top > 0) {
int cell = stack[--top];
int r = cell / C, c = cell % C;
for (int d = 0; d < 4; d++) {
int nr = r + DR[d], nc = c + DC[d];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 1) {
grid[nr][nc] = 0; // sink on push, never on pop
stack[top++] = nr * C + nc;
}
}
}
int cnt = 0;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 1) cnt++;
return cnt;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int numEnclaves(vector<vector<int>>& grid) {
int R = grid.size(), C = grid[0].size();
const int DR[4] = {1, -1, 0, 0}, DC[4] = {0, 0, 1, -1};
// Explicit stack, not recursion. A 500x500 all-land grid is one component
// 250,000 cells deep and overflows the call stack.
vector<int> stk;
stk.reserve(R * C);
for (int r = 0; r < R; r++) {
if (grid[r][0] == 1) { grid[r][0] = 0; stk.push_back(r * C); }
if (grid[r][C - 1] == 1) { grid[r][C - 1] = 0; stk.push_back(r * C + C - 1); }
}
for (int c = 0; c < C; c++) {
if (grid[0][c] == 1) { grid[0][c] = 0; stk.push_back(c); }
if (grid[R - 1][c] == 1) { grid[R - 1][c] = 0; stk.push_back((R - 1) * C + c); }
}
while (!stk.empty()) {
int cell = stk.back(); stk.pop_back();
int r = cell / C, c = cell % C;
for (int d = 0; d < 4; d++) {
int nr = r + DR[d], nc = c + DC[d];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] == 1) {
grid[nr][nc] = 0; // sink on push, never on pop
stk.push_back(nr * C + nc);
}
}
}
int cnt = 0;
for (int r = 0; r < R; r++) for (int c = 0; c < C; c++) if (grid[r][c] == 1) cnt++;
return cnt;
}
};/**
* @param {number[][]} grid
* @return {number}
*/ var numEnclaves = function(grid) {
const R = grid.length, C = grid[0].length;
const DR = [1, -1, 0, 0], DC = [0, 0, 1, -1];
// Explicit stack, not recursion. A 500x500 all-land grid is one component
// 250,000 cells deep and overflows the call stack.
const stack = [];
const seed = (r, c) => {
if (grid[r][c] === 1) {
grid[r][c] = 0;
stack.push(r * C + c);
}
};
for (let r = 0; r < R; r++) {
seed(r, 0);
seed(r, C - 1);
}
for (let c = 0; c < C; c++) {
seed(0, c);
seed(R - 1, c);
}
while (stack.length) {
const cell = stack.pop();
const r = (cell / C) | 0, c = cell % C;
for (let d = 0; d < 4; d++) {
const nr = r + DR[d], nc = c + DC[d];
if (nr >= 0 && nr < R && nc >= 0 && nc < C && grid[nr][nc] === 1) {
grid[nr][nc] = 0; // sink on push, never on pop
stack.push(nr * C + nc);
}
}
}
let cnt = 0;
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) if (grid[r][c] === 1) cnt++;
return cnt;
};