2025-07-31 10:46:42 +0000 UTC

Flood Fill

Code

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        target_color = image[sr][sc]
        enc = set()
        length_row = len(image)
        length_col = len(image[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        queue = [(sr, sc)]
        while queue:
            row, col = queue.pop()
            if row < 0 or row >= length_row:
                continue
            if col < 0 or col >= length_col:
                continue
            if (row, col) in enc:
                continue
            if image[row][col] != target_color:
                continue
            image[row][col] = color
            enc.add((row, col))
            for row_delta, col_delta in dirs:
                queue.append((row + row_delta, col + col_delta))
        return image