-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
733_Flood_Fill.py
41 lines (38 loc) · 1.33 KB
/
733_Flood_Fill.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution(object):
# def floodFill(self, image, sr, sc, newColor):
# """
# :type image: List[List[int]]
# :type sr: int
# :type sc: int
# :type newColor: int
# :rtype: List[List[int]]
# """
# r_ls, c_ls = len(image), len(image[0])
# color = image[sr][sc]
# if color == newColor:
# return image
# def dfs(r, c):
# if image[r][c] == color:
# image[r][c] = newColor
# if r - 1 >= 0: dfs(r - 1, c)
# if r + 1 < r_ls: dfs(r + 1, c)
# if c - 1 >= 0: dfs(r, c - 1)
# if c + 1 < c_ls: dfs(r, c + 1)
# dfs(sr, sc)
# return image
def floodFill(self, image, sr, sc, newColor):
# BFS with queue
r_ls, c_ls = len(image), len(image[0])
color = image[sr][sc]
if color == newColor:
return image
queue = [(sr, sc)]
while len(queue) > 0:
r, c = queue.pop(0)
if image[r][c] == color:
image[r][c] = newColor
if r - 1 >= 0: queue.append((r - 1, c))
if r + 1 < r_ls: queue.append((r + 1, c))
if c - 1 >= 0: queue.append((r, c - 1))
if c + 1 < c_ls: queue.append((r, c + 1))
return image