LeetCode solutions

1073. Number of Enclaves

My accepted Python solution to LeetCode problem 1073, Number of Enclaves, running in 39ms.

  • Difficulty: Medium
  • Python
  • Runtime 39ms
  • Memory 28MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 39ms, memory 28MB, accepted 2026-01-02.

python
class Solution:
    def numEnclaves(self, grid: List[List[int]]) -> int:
        rows, cols = len(grid), len(grid[0])
        
        def dfs(r, c):
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:
                return
            grid[r][c] = 0
            dfs(r + 1, c)
            dfs(r - 1, c)
            dfs(r, c + 1)
            dfs(r, c - 1)
        
        # Remove all land cells connected to the boundary
        for r in range(rows):
            dfs(r, 0)
            dfs(r, cols - 1)
        for c in range(cols):
            dfs(0, c)
            dfs(rows - 1, c)
        
        # Count remaining land cells
        return sum(sum(row) for row in grid)

Source