[LeetCode] Flood Fill (Python)

2024. 3. 9. 10:30알고리즘

 

 

from collections import deque

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        before = image[sr][sc]
        row, col = len(image), len(image[0])
        
        dx = [0, 0, 1, -1]
        dy = [1, -1, 0, 0]
        
        if before != color:
            q = deque()
            q.append([sr, sc])
            
            while q:
                x, y = q.popleft()
                image[x][y] = color
                
                for i in range(4):
                    nx = x + dx[i]
                    ny = y + dy[i]
                    
                    if 0 <= nx < row and 0 <= ny < col and image[nx][ny]== before:
                        q.append((nx, ny))
        return image