Skip to content

Commit cc5c4f1

Browse files
committed
update flood fill.py
1 parent 84c213c commit cc5c4f1

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

Python/Flood_Fill.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,33 @@
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
29
if image[sr][sc] == newColor: return image
10+
11+
#Define a recursive DFS to help us flood fill
312
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
1027
dfs(sr, sc, newColor, image[sr][sc], image)
1128
return image
1229

1330
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))
1532

16-
main()hhh
33+
main()

0 commit comments

Comments
 (0)