本文最后更新于 404 天前,如有失效请评论区留言。
题源:图像渲染
DFS解法:
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        target = image[sr][sc]
        if target == color: return image
        vis = {(sr, sc)}
        def dfs(x, y):
            image[x][y] = color
            for nx, ny in zip((x, x, x+1, x-1), (y+1, y-1, y, y)):
                if 0<=nx<len(image) and 0<=ny<len(image[0]) and image[nx][ny]==target and (nx, ny) not in vis:
                    vis.add((nx, ny))
                    dfs(nx, ny)
        dfs(sr, sc)
        return imageBFS解法:
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        if color == image[sr][sc]:   return image
        q = deque()
        q.append((sr, sc))
        vis = {(sr, sc)}
        target = image[sr][sc]
        while q:
            x, y  = q.popleft()
            image[x][y] = color
            for nx, ny in zip((x, x, x+1, x-1), (y+1, y-1, y, y)):
                if 0 <= nx < len(image) and 0 <= ny < len(image[0]) and image[nx][ny] == target and (nx, ny) not in vis:
                    vis.add((nx, ny))
                    q.append((nx, ny))
        return image