Number of Enclaves
Problem Statement
You are given a grid of 0s (sea) and 1s (land). A move walks from a land cell to a neighbouring land cell (up, down, left or right), or walks off the edge of the grid. Return how many land cells you cannot walk off the edge from, in any number of moves. Those land cells are enclosed.
grid, an m × n grid of 0s and 1s.
The number of land cells that can never reach the edge of the grid.
Three of the 1s are enclosed by 0s. The 1 at the left edge can walk off the grid, so it is not counted.
Every 1 is on the edge, or can walk to the edge through other 1s, so none is enclosed.
- • 1 ≤ m, n ≤ 500, where m is the number of rows and n is the number of columns
- • grid[i][j] is 0 or 1
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each land cell, run a fresh search; count the cell if the search never reaches the edge
Sink every land cell connected to the border; the land still standing is enclosed
For each land cell, run a search over land to see whether it can reach a border cell. If none of the land it reaches is on the border, count the cell. An island with k cells is searched k times, so the same answer is found again and again.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Graph BFS / DFS translate into production architectures and low-level memory mechanics.