Skip to content

Commit 92872d6

Browse files
authored
Merge pull request ashutosh97#93 from arc9693/floodfill-python-sol
Add python implementation of floodfill
2 parents 6aecf61 + c77ae74 commit 92872d6

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

Floodfill/solution.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Python3 program to implement
2+
# flood fill algorithm
3+
4+
# Dimentions of paint screen
5+
M = 8
6+
N = 8
7+
8+
# A recursive function to replace
9+
# previous color 'prevC' at '(x, y)'
10+
# and all surrounding pixels of (x, y)
11+
# with new color 'newC' and
12+
def floodFillUtil(screen, x, y, prevC, newC):
13+
14+
# Base cases
15+
if (x < 0 or x >= M or y < 0 or
16+
y >= N or screen[x][y] != prevC or
17+
screen[x][y] == newC):
18+
return
19+
20+
# Replace the color at (x, y)
21+
screen[x][y] = newC
22+
23+
# Recur for north, east, south and west
24+
floodFillUtil(screen, x + 1, y, prevC, newC)
25+
floodFillUtil(screen, x - 1, y, prevC, newC)
26+
floodFillUtil(screen, x, y + 1, prevC, newC)
27+
floodFillUtil(screen, x, y - 1, prevC, newC)
28+
29+
# It mainly finds the previous color on (x, y) and
30+
# calls floodFillUtil()
31+
def floodFill(screen, x, y, newC):
32+
prevC = screen[x][y]
33+
floodFillUtil(screen, x, y, prevC, newC)
34+
35+
# Driver Code
36+
screen = [[1, 1, 1, 1, 1, 1, 1, 1],
37+
[1, 1, 1, 1, 1, 1, 0, 0],
38+
[1, 0, 0, 1, 1, 0, 1, 1],
39+
[1, 2, 2, 2, 2, 0, 1, 0],
40+
[1, 1, 1, 2, 2, 0, 1, 0],
41+
[1, 1, 1, 2, 2, 2, 2, 0],
42+
[1, 1, 1, 1, 1, 2, 1, 1],
43+
[1, 1, 1, 1, 1, 2, 2, 1]]
44+
45+
x = 4
46+
y = 4
47+
newC = 3
48+
floodFill(screen, x, y, newC)
49+
50+
print ("Updated screen after call to floodFill:")
51+
for i in range(M):
52+
for j in range(N):
53+
print(screen[i][j], end = ' ')
54+
print()

0 commit comments

Comments
 (0)