Skip to main content

2 posts tagged with "Matrix"

View All Tags

class Solution:
def numIslands(self, grid) -> int:
M, N = len(grid), len(grid[0])

def dfs(m, n):
r = 0 <= m < M and 0 <= n < N and grid[m][n] == '1'
if r:
grid[m][n] = None
list(map(dfs, (m + 1, m - 1, m, m), (n, n, n + 1, n - 1)))
return r

return sum(dfs(m, n) for m in range(M) for n in range(N))

class Solution:
def floodFill(
self, image: list[list[int]], sr: int, sc: int, color: int
) -> list[list[int]]:
COLOR, M, N = image[sr][sc], len(image), len(image[0])

def dfs(m, n):
if not all([0 <= m < M, 0 <= n < N]):
return

if not all([image[m][n] == COLOR, image[m][n] != color]):
return

image[m][n] = color
list(map(dfs, (m + 1, m - 1, m, m), (n, n, n + 1, n - 1)))

dfs(sr, sc)
return image