The Number of Enclaves problem gives you a binary matrix where 1 represents land and 0 represents water. Find the number of land cells that cannot reach the boundary by moving only through adjacent land cells. These are "enclosed" land cells. This Number of Enclaves coding problem uses boundary flood-fill followed by counting.
Microsoft, Amazon, Google, and Bloomberg ask this as a direct variant of the flood-fill pattern. It reinforces the "eliminate boundary-connected cells, count the rest" technique. The array, matrix, union find, BFS, and DFS interview pattern is the core, and the problem tests systematic grid traversal with flood-fill.
Boundary flood-fill + count remaining. DFS/BFS from all boundary land cells (value=1), marking them visited (setting to 0 or a separate mark). After all boundary-connected land is eliminated, count the remaining 1-cells. Each remaining cell cannot reach the boundary.
Matrix:
0 0 0 0
1 0 1 0
0 1 1 0
0 0 0 0
Boundary land cells: none (all boundary cells are 0). Interior land cells: (1,2),(2,1),(2,2). From (1,2): can it reach boundary? Only connects to (2,2) which connects to (2,1). None touch boundary → all 3 are enclaves. Count = 3.
Number of Enclaves and Number of Closed Islands are variations of the same pattern: flood-fill from boundaries to eliminate non-enclosed regions, then count what remains. The difference: Closed Islands counts connected groups; Enclaves counts individual cells. Mastering the boundary flood-fill template (iterate all 4 edges, DFS from every boundary land/water cell) solves both problems. Practice this template until boundary edge iteration is automatic.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Closed Islands | Medium | Solve | |
| Maximum Number of Fish in a Grid | Medium | Solve | |
| Detect Cycles in 2D Grid | Medium | Solve | |
| Count Sub Islands | Medium | Solve | |
| Surrounded Regions | Medium | Solve |