Number of Enclaves

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

Example 1
0 0 0 0
1 0 1 0
0 1 1 0
0 0 0 0
Inputgrid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
Output3
There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because it is on the boundary.
Example 2
0 1 1 0
0 0 1 0
0 0 1 0
0 0 0 0
Inputgrid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
Output0
All 1s are either on the boundary or can reach the boundary.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 500
  • grid[i][j] is either 0 or 1.

Asked at 4 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate