We need to answer: Given a 2D grid of 0s and 1s, find number of enclaves: a group of 1s that is completely surrounded by 0s and cannot reach the edge of the grid. Write a function to solve this problem, explain algorithm, and mention traversal algorithm (DFS or BFS) to find land connected to border.
We need to produce code (likely in Python) and explanation.
The problem is known: LeetCode 1020. Number of Enclaves.
Approach: We can do DFS/BFS from all border land cells (i.e., cells with value 1 that are on the boundary). That will mark all land cells that are connected to the border. Then count the remaining land cells in the grid that were not visited/marked. Those are enclaves. Complexity O(m*n). Use either DFS or BFS; both work. For large grid, DFS recursion may hit recursion limit, so iterative BFS or DFS using stack is safer. But we can also use DFS recursion with sys.setrecursionlimit. Usually BFS with queue is used. We'll mention both options but pick BFS for safety.
Algorithm steps:
- Get dimensions m (rows), n (cols).
- Initialize visited matrix or modify grid in-place (set visited land to 0). We'll use grid modification: change visited 1s to 0 to mark as visited.
- For each cell on border (first row, last row, first column, last column) if cell is 1, start BFS/DFS from that cell and mark all connected 1s as visited (set to 0).
- After processing all border-connected land, iterate over entire grid and count remaining 1s (enclaves). That's the answer.
Alternatively, we could use a visited set but in-place modification is efficient.
Edge Cases: grid empty, small grid.
We'll write a function numEnclaves(grid: List[List[int]]) -> int.
We'll implement BFS using collections.deque.
Pseudo:
def bfs(i, j):
queue = deque([(i,j)])
grid[i][j] = 0 # mark visited
while queue:
x, y = queue.popleft()
for dx,dy in dirs:
nx, ny = x+dx, y+dy
if 0 <= nx < m and 0 <= ny < n and grid[nx][ny] == 1:
grid[nx][ny] = 0
queue.append((nx,ny))
Then main:
m,n = len(grid), len(grid[0])
process borders:
for i in range(m):
for j in [0, n-1]:
if grid[i][j] == 1:
bfs(i,j)
for j in range(n):
for i in [0, m-1]:
if grid[i][j] == 1:
bfs(i,j)
count remaining 1s:
return sum(cell for row in grid for cell in row)
But careful: the loops for borders may double-process corners but that's okay because we check if cell is 1; if already set to 0, skip.
Alternatively, combine loops: iterate over all border cells in a single pass.
Complexity: O(mn) time and O(min(m,n)) space? Actually BFS queue could hold up to O(mn) in worst case if all land connected to border. But that's still O(m*n). Could also use iterative DFS with stack to reduce queue overhead.
We'll present BFS.
Now we need to "explain your algorithm". We'll produce a description: The key insight is that any land cell that can reach the border is not an enclave. So we start from border land cells and flood-fill to mark all reachable land. Then count unmarked land.
Also ask: "what traversal algorithm (DFS or BFS) would you use to find the land connected to the border." We'll answer: either DFS (recursive or stack) or BFS; both are fine; BFS is safer for large grids due to no recursion depth limit. We'll choose BFS.
We'll write code with comments.
Potential improvements: Could also use union-find but not needed.
Now we need to produce answer: The function and explanation.
We need to output final answer. We'll include code in Python.
Let's write final answer:
from collections import deque
from typing import List
def numEnclaves(grid: List[List[int]]) -> int:
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
dirs = [(1,0), (-1,0), (0,1), (0,-1)]
def bfs(si, sj):
"""BFS starting from (si,sj) to mark all connected land cells as visited (0)."""
q = deque()
q.append((si, sj))
grid[si][sj] = 0 # mark visited
while q:
i, j = q.popleft()
for di, dj in dirs:
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and grid[ni][nj] == 1:
grid[ni][nj] = 0
q.append((ni, nj))
# Process all border cells
for i in range(m):
# left border
if grid[i][0] == 1:
bfs(i, 0)
# right border
if grid[i][n-1] == 1:
bfs(i, n-1)
for j in range(n):
# top border
if grid[0][j] == 1:
bfs(0, j)
# bottom border
if grid[m-1][j] == 1:
bfs(m-1, j)
# Count remaining 1's (enclaves)
return sum(cell for row in grid for cell in row)
Explanation:
- We treat the grid as a graph where each cell is a node and edges exist between adjacent cells (up/down/left/right).
- An enclave is a connected component of 1's that does not touch the border.
- So we identify and eliminate all components that are connected to the border by performing a BFS (or DFS) from every border cell that contains a 1.
- During BFS we set visited land cells to 0 to mark them as not enclaves and avoid revisiting.
- After all border-connected land is removed, any remaining 1's are part of enclaves; we simply count them.
Time Complexity: O(mn) because each cell is visited at most once during BFS and final counting.
Space Complexity: O(min(m, n)) for BFS queue in worst case (the maximum width of the BFS frontier), but in worst case it could be O(mn) if the whole grid is land; but typical BFS uses O(m*n) worst-case additional space. However, we modify the grid in-place so we don't need an extra visited matrix.
Alternative: Use DFS recursively but may cause recursion depth errors for large grids; iterative DFS with stack works similarly.
We'll also note that we could use DFS, but BFS is chosen to avoid recursion limit.
Now we need to output the answer: function and explanation.
We'll produce a concise but thorough answer.
Solution Overview
An enclave is a group of 1s that is completely surrounded by 0s and cannot reach the grid's edge.
If any land cell (1) can reach a border cell, the whole connected component is not an enclave. Therefore, we can:
- Find all land cells that are connected to the border (using a flood‑fill / graph traversal).
- Mark those cells as visited (e.g., change them to
0).
- After the border‑connected components are removed, count the remaining
1s – they are enclaves.
We’ll use Breadth‑First Search (BFS) for the flood‑fill because it is iterative and avoids recursion depth limits that a recursive DFS might hit on large grids.
Algorithm (Python)
from collections import deque
from typing import List
def numEnclaves(grid: List[List[int]]) -> int:
"""
Returns the number of enclave cells (1's that cannot reach the border).
"""
if not grid or not grid[0]:
return 0
m, n = len(grid), len(grid[0])
directions = [(1,0), (-1,0), (0,1), (0,-1)]
def bfs(si: int, sj: int) -> None:
"""BFS that marks all reachable land cells from (si,sj) as visited (0)."""
q = deque([(si, sj)])
grid[si][sj] = 0 # mark visited
while q:
i, j = q.popleft()
for di, dj in directions:
ni, nj = i + di, j + dj
if 0 <= ni < m and 0 <= nj < n and grid[ni][nj] == 1:
grid[ni][nj] = 0
q.append((ni, nj))
# --- Step 1: eliminate border-connected land ---
# left and right borders
for i in range(m):
if grid[i][0] == 1:
bfs(i, 0)
if grid[i][n-1] == 1:
bfs(i, n-1)
# top and bottom borders
for j in range(n):
if grid[0][j] == 1:
bfs(0, j)
if grid[m-1][j] == 1:
bfs(m-1, j)
# --- Step 2: count remaining (enclave) cells ---
return sum(cell for row in grid for cell in row)
Explanation of Key Steps
-
Border Processing
We iterate over all cells lying on the four edges of the grid.
- If a border cell contains
1, we start a BFS from it.
- The BFS explores all 4‑directionally adjacent land cells, turning them into
0s (visited).
- This removes the entire connected component that touches the border.
-
Counting Enclaves
After the first pass, every 1 left in the grid is part of a component that never reached the border, i.e., an enclave. A simple sum over all cells yields the answer.
Why BFS?
- No recursion depth issue – BFS is implemented iteratively with a queue.
- Same time/space complexity as DFS for this problem.
- Intuitive for “flood‑fill” from a starting frontier.
If one prefers DFS, an iterative stack can be used, or recursion with sys.setrecursionlimit, but BFS is typically safer for large inputs.
Complexity Analysis
- Time:
O(m * n) – each cell is visited at most once (either during BFS or the final counting).
- Space:
O(m * n) worst‑case for the BFS queue (when the whole grid is land). In practice it’s O(min(m, n)) for the queue’s maximum width. The grid is modified in‑place, so no extra visited matrix is needed.
Edge Cases Handled
- Empty grid → return
0.
- Single row/column → border processing still works correctly.
- Multiple disconnected border components → each is eliminated independently.
This solution efficiently counts enclaves by subtracting border‑connected land from the total land.