Number of Enclaves

You are given an m x n binary matrix grid, where 0 is a sea cell and 1 is a land cell. A move walks from one land cell to an adjacent (4-directional) land cell or walks off the boundary of the grid. Return the number of land cells from which we cannot walk off the boundary of the grid in any number of moves.

30:00

Number of Enclaves
medium
Free written solution
Topics
Companies

You are given an m x n binary matrix grid, where 0 is a sea cell and 1 is a land cell. A move walks from one land cell to an adjacent (4-directional) land cell or walks off the boundary of the grid. Return the number of land cells from which we cannot walk off the boundary of the grid in any number of moves.

Example 1:
Input: {"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]}
Output: 3
Constraints:
  • m==grid.lengthm == \text{grid.length}

  • n==grid[i].lengthn == \text{grid}[i].\text{length}

  • 1≤m,n≤5001 \leq m, n \leq 500

  • grid[i][j]\text{grid}[i][j] is either 0 or 1.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"grid":[[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]}

The grid is 4 x 4 with 4 land cells. Instead of asking which cells are trapped, find every cell that CAN walk off the edge, starting from the border.

■ land, not yet known

↗ can walk off (0)

■ trapped (0)

■ water

stack (0)

empty

enclave cells

? (4 unknown)

Variables
VariableValue
m4
n4
stack0
count0
DepthFunction Call
Stack empty
0/7