Flood Fill LeetCode solution in Python

1
class Solution:
2
def floodFill(
3
self, image: List[List[int]], sr: int, sc: int, color: int
4
) -> List[List[int]]:
5
queue = deque()
6
rows = len(image)
7
cols = len(image[0])
8

9
targetColor = image[sr][sc]
10

11
if color == targetColor:
12
# in this case, we don't need to do anything
13
return image
14

15
rDirs = [1, 0, -1, 0]
16
cDirs = [0, 1, 0, -1]
17

18
queue.append((sr, sc))
19

20
while len(queue) > 0:
21
r, c = queue.pop()
22

23
image[r][c] = color
24
for rd, cd in zip(rDirs, cDirs):
25
newRow = r + rd
26
newCol = c + cd
27

28
isValidCoordinate = (
29
newRow >= 0 and newRow < rows and newCol >= 0 and newCol < cols
30
)
31

32
if isValidCoordinate and image[newRow][newCol] == targetColor:
33
queue.append((newRow, newCol))
34

35
return image

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0