1020. Number of Enclaves
Description
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:
Input: grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]] Output: 3 Explanation: There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
Example 2:
Input: grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]] Output: 0 Explanation: 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 either0
or1
.
Solution
number-of-enclaves.py
class Solution:
def numEnclaves(self, grid: List[List[int]]) -> int:
rows, cols = len(grid), len(grid[0])
res = 0
visited = [[False] * cols for _ in range(rows)]
def go(x, y):
if x == 0 or x == rows - 1 or y == 0 or y == cols - 1:
self.metBoundary = True
count = 1
for dx, dy in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if 0 <= dx < rows and 0 <= dy < cols and grid[dx][dy] == 1 and not visited[dx][dy]:
visited[dx][dy] = True
count += go(dx, dy)
return count
for x in range(rows):
for y in range(cols):
if grid[x][y] == 1 and not visited[x][y]:
self.metBoundary = False
visited[x][y] = True
size = go(x, y)
if not self.metBoundary:
res += size
return res