|
| 1 | +""" |
| 2 | +Problem Link: https://leetcode.com/problems/flood-fill/ |
| 3 | +
|
| 4 | +An image is represented by a 2-D array of integers, each integer representing the pixel |
| 5 | +value of the image (from 0 to 65535). |
| 6 | +Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, |
| 7 | +and a pixel value newColor, "flood fill" the image. |
| 8 | +To perform a "flood fill", consider the starting pixel, plus any pixels connected 4-directionally |
| 9 | +to the starting pixel of the same color as the starting pixel, plus any pixels connected |
| 10 | +4-directionally to those pixels (also with the same color as the starting pixel), and so on. |
| 11 | +Replace the color of all of the aforementioned pixels with the newColor. |
| 12 | +
|
| 13 | +At the end, return the modified image. |
| 14 | +
|
| 15 | +Example 1: |
| 16 | +Input: |
| 17 | +image = [[1,1,1],[1,1,0],[1,0,1]] |
| 18 | +sr = 1, sc = 1, newColor = 2 |
| 19 | +Output: [[2,2,2],[2,2,0],[2,0,1]] |
| 20 | +Explanation: |
| 21 | +From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected |
| 22 | +by a path of the same color as the starting pixel are colored with the new color. |
| 23 | +Note the bottom corner is not colored 2, because it is not 4-directionally connected |
| 24 | +to the starting pixel. |
| 25 | +Note: |
| 26 | +
|
| 27 | +The length of image and image[0] will be in the range [1, 50]. |
| 28 | +The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length. |
| 29 | +The value of each color in image[i][j] and newColor will be an integer in [0, 65535]. |
| 30 | +""" |
| 31 | +class Solution: |
| 32 | + def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: |
| 33 | + m, n = len(image), len(image[0]) |
| 34 | + color = image[sr][sc] |
| 35 | + |
| 36 | + if color == newColor: |
| 37 | + return image |
| 38 | + |
| 39 | + def dfs(i, j): |
| 40 | + if image[i][j] == color: |
| 41 | + image[i][j] = newColor |
| 42 | + if i >= 1: |
| 43 | + dfs(i-1, j) |
| 44 | + if j >= 1: |
| 45 | + dfs(i, j-1) |
| 46 | + if i < m-1: |
| 47 | + dfs(i+1, j) |
| 48 | + if j < n-1: |
| 49 | + dfs(i, j+1) |
| 50 | + |
| 51 | + dfs(sr, sc) |
| 52 | + return image |
0 commit comments