Leetcode #1020: Number of Enclaves
In this guide, we solve Leetcode #1020 Number of Enclaves in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an m x n binary matrix grid, where 0 represents a sea cell and 1 represents a land cell. A move consists of walking from one land cell to another adjacent (4-directionally) land cell or walking off the boundary of the grid.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
Python Solution
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int):
grid[i][j] = 0
for a, b in pairwise(dirs):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and grid[x][y]:
dfs(x, y)
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
for j in range(n):
if grid[0][j]:
dfs(0, j)
if grid[m - 1][j]:
dfs(m - 1, j)
for i in range(m):
if grid[i][0]:
dfs(i, 0)
if grid[i][n - 1]:
dfs(i, n - 1)
return sum(sum(row) for row in grid)
Complexity
The time complexity is O(V+E). The space complexity is O(V).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.