Problem
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
.
Return the number of land cells in grid
for which we cannot walk off the boundary of the grid in any number of moves.
Examples
Example 1:
$$ \begin{array}{|c|c|c|c|} \hline \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 \\ \hline \colorbox{yellow} 1 & \colorbox{Cerulean} 0 & \colorbox{pink} 1 & \colorbox{Cerulean} 0 \\ \hline \colorbox{Cerulean} 0 & \colorbox{pink} 1 & \colorbox{pink} 1 & \colorbox{Cerulean} 0 \\ \hline \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 \\ \hline \end{array} $$
|
|
Example 2:
$$ \begin{array}{|c|c|c|c|} \hline \colorbox{Cerulean} 0 & \colorbox{yellow} 1 & \colorbox{yellow} 1 & \colorbox{Cerulean} 0 \\ \hline \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{yellow} 1 & \colorbox{Cerulean} 0 \\ \hline \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{yellow} 1 & \colorbox{Cerulean} 0 \\ \hline \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 & \colorbox{Cerulean} 0 \\ \hline \end{array} $$
|
|
Solution
Method 1 – DFS to Remove Edge-Connected Land
Intuition
The key idea is to use DFS to “sink” all land cells (1
s) that are connected to the boundary of the grid. Any land cell that can reach the boundary is not an enclave. After removing all such cells, the remaining land cells are those that are completely surrounded by sea (0
s) and cannot reach the boundary.
Approach
- Iterate over all boundary cells (first and last row, first and last column).
- For each boundary cell that is land (
1
), perform DFS to mark all connected land cells as sea (0
). - After processing all boundaries, count the number of land cells (
1
s) left in the grid. These are the enclaves.
Complexity
- ⏰ Time complexity:
O(m * n)
, wherem
andn
are the grid dimensions, since each cell is visited at most once. - 🧺 Space complexity:
O(m * n)
in the worst case due to the recursion stack.
Code
|
|
|
|
|
|