AlgoInsight

DSA problem

Number of Enclaves

MediumDepth First Search (DFS)Pattern: Depth First Search (DFS)top600AmazonMicrosoftGoogleBloombergApple

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 the grid for which we cannot walk off the boundary in any number of moves.

The set of cells that we cannot escape from is exactly the set of land cells that are not connected to any border-adjacent land cell. Equivalently, a land cell is "enclaved" if and only if it cannot reach the border by moving only through 1-cells. Instead of trying to test every cell individually, we flip the perspective: identify the cells that can escape and exclude them.

The optimal approach is a flood-fill from the border. Walk the four edges of the grid; for every 1 cell on the border, run a DFS or BFS that visits every connected land cell and either marks them as visited or zeroes them out in-place. After the flood-fill completes, every remaining 1 in the grid is unreachable from any border, so the answer is the number of remaining 1s.

This costs O(m * n) time because every cell is processed at most twice (once by the flood-fill from the border and once by the final counting pass), and O(m * n) space in the worst case for the recursion/queue depth when the grid is one giant connected land mass.

Examples

Example 1
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output: 3
Explanation: None of the inner land cells touch the border, so all three remain after the boundary flood-fill — the answer is 3.
Example 2
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output: 0
Explanation: Every land cell is connected to a border land cell, so all of them can escape — no enclaves remain.
Example 3
Input: grid = [[0,0,0,1],[0,1,1,0],[0,1,0,0],[0,0,0,0]]
Output: 3
Explanation: The 1 at (0,3) is on the border so its component escapes; the inner triangle of three 1s is isolated — the answer is 3.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dfsbfsmatrixflood-fill

Browse all DSA problems