Number of Enclaves (LeetCode 1020): Solution and Explanation
In a grid of land (1) and sea (0), you can walk between neighbouring land cells and step off the grid from boundary land. Count the land cells that can never reach the edge.
Intuition
Asking each land cell whether it can escape would mean one search per cell. Turn the question around: which cells can escape? Exactly those connected to a land cell on the boundary.
So start at the border. Every boundary land cell can step off immediately, and anything connected to it can walk there first. One flood fill seeded with all boundary land marks every cell that escapes.
Whatever land the flood never touches is cut off by sea on all sides. Those are the enclave cells, and the answer is simply how many of them are left.
Approach: Multi-source flood fill from the boundary
- Scan the grid and push every land cell on the first or last row or column, sinking it (set it to 0) so it is not counted.
- While the stack is not empty, pop a cell and push every land neighbour, sinking it as well.
- After the flood, every remaining 1 is unreachable from the edge.
- Return the number of remaining 1s.
Step-by-step example
grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
- The only boundary land cell is (1,0). Sink it and push it.
- Pop (1,0). Its neighbours (0,0), (2,0) and (1,1) are all sea, so nothing else is sunk.
- The stack is empty. The land left is (1,2), (2,1) and (2,2).
- None of them touched the flood, so they are enclosed. Return 3.
Code: Python, Java, C++
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 if (r == 0 or c == 0 or r == m - 1 or c == n - 1) and grid[r][c] == 1:
8 grid[r][c] = 0
9 stack.append((r, c))
10 while stack:
11 x, y = stack.pop()
12 for nx, ny in ((x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)):
13 if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 1:
14 grid[nx][ny] = 0
15 stack.append((nx, ny))
16 return sum(map(sum, grid))1class Solution {
2 public int numEnclaves(int[][] grid) {
3 int m = grid.length, n = grid[0].length;
4 Deque<int[]> stack = new ArrayDeque<>();
5 for (int r = 0; r < m; r++) {
6 for (int c = 0; c < n; c++) {
7 if ((r == 0 || c == 0 || r == m - 1 || c == n - 1) && grid[r][c] == 1) {
8 grid[r][c] = 0;
9 stack.push(new int[]{r, c});
10 }
11 }
12 }
13 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
14 while (!stack.isEmpty()) {
15 int[] cell = stack.pop();
16 for (int[] d : dirs) {
17 int nx = cell[0] + d[0], ny = cell[1] + d[1];
18 if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1) {
19 grid[nx][ny] = 0;
20 stack.push(new int[]{nx, ny});
21 }
22 }
23 }
24 int count = 0;
25 for (int[] row : grid) {
26 for (int v : row) count += v;
27 }
28 return count;
29 }
30}1class Solution {
2public:
3 int numEnclaves(vector<vector<int>>& grid) {
4 int m = grid.size(), n = grid[0].size();
5 vector<pair<int, int>> st;
6 for (int r = 0; r < m; r++) {
7 for (int c = 0; c < n; c++) {
8 if ((r == 0 || c == 0 || r == m - 1 || c == n - 1) && grid[r][c] == 1) {
9 grid[r][c] = 0;
10 st.push_back({r, c});
11 }
12 }
13 }
14 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
15 while (!st.empty()) {
16 int x = st.back().first, y = st.back().second;
17 st.pop_back();
18 for (auto& d : dirs) {
19 int nx = x + d[0], ny = y + d[1];
20 if (nx >= 0 && nx < m && ny >= 0 && ny < n && grid[nx][ny] == 1) {
21 grid[nx][ny] = 0;
22 st.push_back({nx, ny});
23 }
24 }
25 }
26 int count = 0;
27 for (auto& row : grid) {
28 for (int v : row) count += v;
29 }
30 return count;
31 }
32};Time and space complexity
O(m * n)
Every cell is scanned once, and each land cell is pushed and popped at most once.
O(m * n)
The stack can hold every land cell when one big island touches the border.
Other approaches
Union-Find with a virtual edge node (time O(m * n α(m * n)), space O(m * n))
Union every boundary land cell with a special edge node and every pair of adjacent land cells with each other. Count land cells whose root is not the edge node's root.
Flood each island and check if it touches the edge (time O(m * n), space O(m * n))
Flood fill every island from inside, tracking its size and whether any cell is on the boundary. Add the size of islands that never touched it. Same complexity, slightly more bookkeeping.
Common mistakes
- Starting a separate search from every land cell, which is O((m * n)^2) on a big island.
- Forgetting that diagonal neighbours do not count. Only up, down, left and right connect land.
- Recursive DFS on a 500 x 500 grid can hit the recursion limit in Python or overflow the stack elsewhere. Use an explicit stack or queue.
- Marking a cell only when it is popped. The same cell can then be pushed several times; mark it as soon as you push it.
Frequently asked questions
Is this the same as Number of Closed Islands?
It is close. Closed Islands counts islands that do not touch the border, while this problem counts land cells. The same border flood works for both; only the final count differs.
Can I modify the input grid?
The standard solution sinks reached cells in place to avoid a separate visited array. If you must keep the grid, use a boolean visited matrix instead.
Does BFS or DFS matter here?
No. Any traversal that reaches every land cell connected to the border gives the same set of marked cells.