#1020
Number of Enclaves
MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixDepth-First SearchBreadth-First SearchGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n²)Space O(1)
The optimal approach uses a modified DFS or BFS to mark all land cells connected to the boundary. This way, we can efficiently count the remaining land cells that are enclaves.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through the boundary cells of the grid.
- 2Step 2: For each land cell (1) found on the boundary, perform a DFS/BFS to mark all reachable land cells as visited.
- 3Step 3: After marking, count the remaining land cells (1s) that are not visited.
solution.py16 lines
1def numEnclaves(grid):
2 def dfs(x, y):
3 if x < 0 or x >= len(grid) or y < 0 or y >= len(grid[0]) or grid[x][y] == 0:
4 return
5 grid[x][y] = 0 # Mark as visited
6 dfs(x + 1, y)
7 dfs(x - 1, y)
8 dfs(x, y + 1)
9 dfs(x, y - 1)
10
11 for i in range(len(grid)):
12 for j in range(len(grid[0])):
13 if (i == 0 or i == len(grid) - 1 or j == 0 or j == len(grid[0]) - 1) and grid[i][j] == 1:
14 dfs(i, j)
15
16 return sum(row.count(1) for row in grid)ℹ
Complexity note: The time complexity remains O(n²) since we still potentially visit every cell in the grid. The space complexity is O(1) as we are modifying the grid in place without using additional data structures.
- 1Cells on the boundary can directly reach the edge and are not enclaves.
- 2Using DFS/BFS allows us to efficiently mark connected components.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.