1
- def floodFill (image , sr , sc , newColor ):
1
+ #Question: Given a image (2D list), a x and y coordinate of a pixel, and a new color, flood fill all neigbboring pixels with the same color to the new color
2
+ #Solution: Run a DFS on the input pixel
3
+ #Difficulty: Easy
4
+
5
+ from typing import List
6
+ def floodFill (image : List [List [int ]], sr : int , sc : int , newColor : int ) -> List [List [int ]]:
7
+
8
+ #If the pixel at the given coordinates is already the new color, return the image
2
9
if image [sr ][sc ] == newColor : return image
10
+
11
+ #Define a recursive DFS to help us flood fill
3
12
def dfs (i , j , newColor , oldColor , image ):
4
- if i >= 0 and j >= 0 and i < len (image ) and j < len (image [0 ]) and image [i ][j ] == oldColor :
5
- image [i ][j ] = newColor
6
- dfs (i + 1 , j , newColor , oldColor , image )
7
- dfs (i - 1 , j , newColor , oldColor , image )
8
- dfs (i , j + 1 , newColor , oldColor , image )
9
- dfs (i , j - 1 , newColor , oldColor , image )
13
+
14
+ #If the coordinates passed are not out of bounds and the color is the same as the previous one
15
+ if i >= 0 and j >= 0 and i < len (image ) and j < len (image [0 ]) and image [i ][j ] == oldColor :
16
+
17
+ #Set the pixel at the given coordinates to the new color
18
+ image [i ][j ] = newColor
19
+
20
+ #Recursively repeat on the pixel left, right, above and below
21
+ dfs (i + 1 , j , newColor , oldColor , image )
22
+ dfs (i - 1 , j , newColor , oldColor , image )
23
+ dfs (i , j + 1 , newColor , oldColor , image )
24
+ dfs (i , j - 1 , newColor , oldColor , image )
25
+
26
+ #Call our DFS function on the original inputs
10
27
dfs (sr , sc , newColor , image [sr ][sc ], image )
11
28
return image
12
29
13
30
def main ():
14
- print (floodFill ([[0 ,0 ,0 ],[0 ,1 ,1 ]], 1 , 1 , 1 ))
31
+ print (floodFill ([[0 ,0 ,0 ],[0 ,1 ,1 ]], 0 , 0 , 6 ))
15
32
16
- main ()hhh
33
+ main ()
0 commit comments