-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathflood-fill.py
54 lines (45 loc) · 1.98 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution:
def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
color_to_replace = image[sr][sc]
visited = set((sr, sc))
stack = [(sr, sc)]
image[sr][sc] = newColor
while stack:
row, column = stack.pop()
for neigh_row, neigh_column in [
(row + 1, column),
(row - 1, column),
(row, column + 1),
(row, column - 1),
]:
if 0 <= neigh_row < len(image) and \
0 <= neigh_column < len(image[0]) and \
image[neigh_row][neigh_column] == color_to_replace and \
not (neigh_row, neigh_column) in visited:
stack.append((neigh_row, neigh_column))
visited.add((neigh_row, neigh_column))
image[neigh_row][neigh_column] = newColor
return image
def floodFillBFS(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
color_to_replace = image[sr][sc]
visited = set((sr, sc))
stack = [(sr, sc)]
image[sr][sc] = newColor
while stack:
tmp_stack = stack
stack = []
for row, column in tmp_stack:
for neigh_row, neigh_column in [
(row + 1, column),
(row - 1, column),
(row, column + 1),
(row, column - 1),
]:
if 0 <= neigh_row < len(image) and \
0 <= neigh_column < len(image[0]) and \
image[neigh_row][neigh_column] == color_to_replace and \
not (neigh_row, neigh_column) in visited:
stack.append((neigh_row, neigh_column))
visited.add((neigh_row, neigh_column))
image[neigh_row][neigh_column] = newColor
return image