Understanding the Problem
In this problem, we are given a grid with 0s and 1s, where 1
represents land and 0
represents water. An enclave is a group of land cells that cannot reach the boundary of the grid by moving in 4 directions (up, down, left, right).
Boundary Land Cells
The first thing to observe is that any land cell connected to the boundary (first or last row/column) cannot be part of an enclave. So we start by marking all land cells that are reachable from the boundary using either BFS or DFS.
Marking Reachable Land
We traverse the boundary of the grid. If we find a 1
, we launch a DFS or BFS to mark all connected land cells as visited. These cells are not enclaves since they can reach the boundary directly or indirectly.
Counting Enclaves
After marking all boundary-connected land, we iterate through the internal cells of the grid. Any land cell that is still unvisited is an enclave because it cannot reach the boundary. We count and return these cells.
Example
For a grid like:
[[0,0,0,0],
[1,0,1,0],
[0,1,1,0],
[0,0,0,0]]
The land cells at (1,2), (2,1), and (2,2) are not connected to the boundary, so they are considered enclaves. The result will be 3.
Edge Cases
- Empty Grid: Return 0 because there are no land cells.
- All Boundary Land: Return 0 because all land is connected to boundary.
- Full Land but Enclosed: Internal land surrounded by water will be counted correctly.