1254. Number of Closed Islands
LAND = 0
WATER = 1
VISITED = -1
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
def bfs(y, x):
q = collections.deque([[y, x]])
grid[y][x] = VISITED
is_closed = True
while q:
y, x = q.popleft()
if y == 0 or y == M-1 or x == 0 or x == N-1:
is_closed = False
for dx, dy in ((-1, 0), (1, 0), (0, -1), (0, 1)):
nx = x + dx
ny = y + dy
if 0 <= nx < N and 0 <= ny < M and grid[ny][nx] == LAND:
grid[ny][nx] = VISITED
q.append([ny, nx])
return 1 if is_closed else 0
M, N = len(grid), len(grid[0])
closed_islands = 0
for i in range(M):
for j in range(N):
if grid[i][j] == LAND:
closed_islands += bfs(i, j)
return closed_islands