Count the land cells in a grid that cannot reach the boundary by moving through adjacent land cells.
You are given a 2D grid of binary values where 1 represents land and 0 represents water. A land cell is part of an enclave if it belongs to a connected region of land that cannot reach any border of the grid by moving only up, down, left, or right through land cells.
Return the number of land cells that are enclosed in this way.
In other words, first identify every land cell that can be connected to the boundary, then count the remaining land cells.
grid with grid[i][j] in {0, 1}.1 means land and 0 means water.Example 1
Input
grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output
3
Explanation
The land cells at positions (1,2), (2,1), and (2,2) are enclosed. The land cell at (1,0) touches the boundary, so it is not counted.
Example 2
Input
grid = [[0,1,1,0],[0,0,1,0],[0,0,0,0]]
Output
0
Explanation
Every land cell can reach the boundary through adjacent land cells, so there are no enclaves.
Premium problem context
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.