Skip to content

Commit 5143a13

Browse files
authored
Create 733-flood_fill.py
1 parent 53aec4d commit 5143a13

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

Diff for: 733-flood_fill.py

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
"""
2+
https://leetcode.com/problems/flood-fill/submissions/
3+
4+
Stats: O(n) time, O(n) space
5+
Runtime: 72 ms, faster than 23.24% of Python online submissions for Flood Fill.
6+
Memory Usage: 13 MB, less than 24.83% of Python online submissions for Flood Fill.
7+
"""
8+
class Solution(object):
9+
"""
10+
First take (uses unecessary set)
11+
"""
12+
def floodFill(self, image, source_row, source_col, new_color):
13+
"""
14+
:type image: List[List[int]]
15+
:type sr: int
16+
:type sc: int
17+
:type newColor: int
18+
:rtype: List[List[int]]
19+
"""
20+
visited = set()
21+
self.old_color = image[source_row][source_col]
22+
self.image = image
23+
24+
def fill(sr, sc):
25+
if (str(sr) + str(sc)) in visited:
26+
return
27+
28+
visited.add(str(sr) + str(sc))
29+
30+
length = len(self.image)
31+
height = len(self.image[0])
32+
33+
# print(visited)
34+
# print(sr, sc)
35+
# print(self.image)
36+
37+
if 0 <= sr < length and 0 <= sc < height: #check bounds
38+
if self.image[sr][sc] == self.old_color:
39+
self.image[sr][sc] = new_color
40+
# print("updated {} {} ".format(sr, sc))
41+
# print(self.image)
42+
# print("")
43+
44+
#check four sides
45+
fill(sr + 1, sc)
46+
fill(sr - 1, sc)
47+
fill(sr, sc + 1)
48+
fill(sr, sc - 1)
49+
50+
# do our fill work
51+
fill(source_row, source_col)
52+
53+
return self.image
54+
55+
"""
56+
Improved -- no set & uses clever bounds checking
57+
"""
58+
def floodFill(self, image, source_row, source_col, new_color):
59+
"""
60+
:type image: List[List[int]]
61+
:type sr: int
62+
:type sc: int
63+
:type newColor: int
64+
:rtype: List[List[int]]
65+
"""
66+
if image[source_row][source_col] == new_color:
67+
return image
68+
69+
old_color = image[source_row][source_col]
70+
71+
def fill(sr, sc):
72+
if sr < 0 or sc < 0:
73+
return
74+
75+
# use exception handling instead of bounds checking
76+
try:
77+
if image[sr][sc] == old_color:
78+
image[sr][sc] = new_color
79+
80+
#check four sides
81+
fill(sr + 1, sc)
82+
fill(sr - 1, sc)
83+
fill(sr, sc + 1)
84+
fill(sr, sc - 1)
85+
except: #MUST have this otherwise error!
86+
return
87+
88+
# do the dfs dirty work
89+
fill(source_row, source_col)
90+
return image

0 commit comments

Comments
 (0)