733. Flood Fill - cocoder39/coco39_LC GitHub Wiki

733. Flood Fill

stack overflow is the edge case where image[sr][sc] == newColor is not handled

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        if image[sr][sc] != newColor:
            self.fill(sr, sc, image, image[sr][sc], newColor)
        return image
    
    def fill(self, cur_row: int, cur_col: int, image: List[List[int]], original_col: int, new_color: int):
        image[cur_row][cur_col] = new_color
        
        row_count, col_count = len(image), len(image[0])
        for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            new_row, new_col = cur_row + dr, cur_col + dc
            if 0 <= new_row < row_count and 0 <= new_col < col_count and image[new_row][new_col] == original_col:
                self.fill(new_row, new_col, image, original_col, new_color)