SDE & MLE Prep

733. Flood Fill

Problem

Starting at pixel (sr, sc), recolour it and every pixel connected to it (up, down, left, right) through pixels of the same original colour with color, and return the image.

Example: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2 → [[2,2,2],[2,2,0],[2,0,1]]

DFS/BFS from the start cell through 4-neighbours that have the original color, recoloring as you go. If the new color equals the original, return immediately — otherwise the search never terminates (recolored cells still match).

Complexity: O(R·C).

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        old = image[sr][sc]
        if old == color:
            return image
        R, C = len(image), len(image[0])
        image[sr][sc] = color
        stack = [(sr, sc)]
        while stack:
            r, c = stack.pop()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == old:
                    image[nr][nc] = color
                    stack.append((nr, nc))
        return image