-
Notifications
You must be signed in to change notification settings - Fork 0
/
flood_fill.py
56 lines (39 loc) · 1.25 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
55
56
def flood_fill(r, c, replacement, image):
# get all pixels connected to the pixel at (r, c)
# with the same color
connected = get_connected(image, r, c)
# set all those pixels to be REPLACEMENT color
for row, col in connected:
image[row][col] = replacement
return image
# Run DFS to get all pixels connected to the pixel at (r, c)
# with the same color as the pixel at (r, c).
def get_connected(image, r, c):
if not image:
return []
color = image[r][c]
stack = [(r, c)]
seen = set()
while stack:
nxt = stack.pop()
if nxt in seen:
continue
r, c = nxt
for neighbor in get_neighbors(image, r, c):
row, col = neighbor
if image[row][col] == color:
stack.append((row, col))
seen.add(nxt)
return list(seen)
def get_neighbors(matrix, r, c):
if not matrix:
return []
neighbors = []
numRows = len(matrix)
numCols = len(matrix[0])
OFFSETS = [(-1,0), (1,0), (0,1), (0,-1)]
for rowOffset, colOffset in OFFSETS:
if 0 <= r + rowOffset <= numRows-1:
if 0 <= c + colOffset <= numCols-1:
neighbors.append((r + rowOffset, c + colOffset))
return neighbors