1254. Number of Closed Islands
https://leetcode.com/problems/number-of-closed-islands
Python
DFS
class Solution:
def closedIsland(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
# 0: Not visited island block
# 1: Water
# 2: Visited island block
def dfs(i: int, j: int) -> bool:
if i < 0 or j < 0 or i >= m or j >= n:
return True
if grid[i][j] > 0:
return False
grid[i][j] = 2
return any([
dfs(i+rx, j+cx)
for rx, cx
in [(-1, 0), (1, 0), (0, -1), (0, 1)]
])
ans = 0
for i in range(m):
for j in range(n):
if grid[i][j] == 0 and not dfs(i, j):
ans += 1
return ans