-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfloodfill.py
More file actions
24 lines (22 loc) · 813 Bytes
/
floodfill.py
File metadata and controls
24 lines (22 loc) · 813 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# https://binarysearch.com/problems/Paint-Bucket
class Solution:
def bounds(self, matrix, r, c):
return 0 <= r < len(matrix) and 0 <= c < len(matrix[0])
def solve(self, matrix, r, c, target):
seen = set()
original = matrix[r][c]
stack = [(r, c)]
while len(stack) > 0:
r_, c_ = stack.pop()
matrix[r_][c_] = target
nbrs = [(r_-1,c_), (r_,c_-1), (r_+1,c_), (r_,c_+1)]
for r_n, c_n in nbrs:
if not self.bounds(matrix, r_n, c_n):
continue
if (r_n, c_n) in seen:
continue
if matrix[r_n][c_n] != original:
continue
stack.append((r_n, c_n))
seen.add((r_n, c_n))
return matrix