Number of Enclaves

Given a grid of land and water, return the number of land cells that cannot reach the boundary by moving only in four directions. Pattern focus: Component traversal. Traverse each land component and ignore the ones that touch the border.

Input Format

grid = 2D binary matrix

Output Format

count of enclave land cells

Constraints

  • 1 <= rows * cols <= 10^5
  • Each cell is 0 or 1.

Examples

Example 1:

Input:

grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]

Output:

3

Explanation:

Three land cells are fully enclosed away from the boundary.

Example 2:

Input:

grid = [[1,1,1],[1,0,1],[1,1,1]]

Output:

0

Explanation:

Every land cell touches the border through the component.

Example 3:

Input:

grid = [[0,0],[0,0]]

Output:

0

Explanation:

There is no land.

Loading...
Number of Enclaves - Graph Traversal DSA Problem