You're exploring a mysterious archipelago represented by a binary matrix where 0 represents water and 1 represents land. Your goal is to find landlocked islands - pieces of land that are completely surrounded by water or other land, with no path to escape to the ocean.
Think of it this way: if you were standing on a land cell, you can move in 4 directions (up, down, left, right) to adjacent land cells. If there's any possible path that leads you to the boundary of the grid (the edge where you can "walk off" into the ocean), then that land is not an enclave.
Return the total number of land cells that form enclaves - land from which you cannot reach the boundary no matter how many moves you make.
Example: In a 4×4 grid, if there's a small island in the center completely surrounded by water or boundary-connected land, those center cells would be enclaves.
💡 Note:There are three enclaves: the isolated '1' cells that cannot reach any boundary. The cells at positions (1,0) and (1,2) can potentially reach boundaries, but (2,1) and (2,2) form an enclave that cannot.
💡 Note:All land cells are connected to the boundary through the top-right corner land cell, so there are no enclaves. Every '1' can trace a path to the edge.
💡 Note:The entire inner island is surrounded by water and cannot reach any boundary. All 8 land cells form one large enclave completely isolated from the edges.
The optimal approach uses reverse thinking: instead of checking if each cell can reach the boundary, start from the boundary and mark all reachable land. The key insight is to perform DFS from all boundary land cells first, then count the remaining unmarked land cells. This achieves O(m×n) time complexity by visiting each cell at most twice, making it significantly more efficient than checking each cell individually.
Common Approaches
✓
Boundary DFS + Counting (Optimal)
⏱️ Time: O(m×n)
Space: O(m×n)
This optimal approach reverses the problem: instead of checking if each cell can reach the boundary, we start from the boundary and mark all reachable land cells. The remaining unmarked land cells are enclaves.
Brute Force (DFS from Each Cell)
⏱️ Time: O(m²×n²)
Space: O(m×n)
This naive approach examines every land cell individually and performs a depth-first search to determine if there's any path from that cell to the grid boundary. If a path exists, the cell is not an enclave.