Problems/1020. Number of Enclaves

1020. Number of Enclaves

MediumMatrixGraphDFSBFS

You are given a 2D matrix of size m x n containing land cells (1s) and water cells (0s).

A land cell is an enclave if it is impossible to walk off the edge of the grid by stepping only 4-directionally on land cells. Find the total count of such enclaved land cells in the grid.

Example 1
Input: grid = [ [0, 0, 0, 0], [1, 0, 1, 0], [0, 1, 1, 0], [0, 0, 0, 0] ]
Output: 3
There are three land cells in the center that are enclaves because they are surrounded by water and cannot reach any edge.
Example 2
Input: grid = [ [0, 1, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 0] ]
Output: 0
All land cells are connected to the top edge, meaning they can all reach the boundary. Thus, there are 0 enclaves.
Example 3
Input: grid = [ [0, 0, 0], [0, 1, 0], [0, 0, 0] ]
Output: 1
The single land cell in the center has no path to the boundary, forming 1 enclave.
Visualizer

Visualizer will appear here