-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfloodfill.py
55 lines (47 loc) · 1.72 KB
/
floodfill.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
import sys
# Create the image (make sure it's rectangular!)
im = [list('..########################...........'),
list('..#......................#...#####...'),
list('..#..........########....#####...#...'),
list('..#..........#......#............#...'),
list('..#..........########.........####...'),
list('..######......................#......'),
list('.......#..#####.....###########......'),
list('.......####...#######................')]
HEIGHT = len(im)
WIDTH = len(im[0])
def floodFill(image, x, y, newChar, oldChar=None):
if oldChar == None:
# oldChar defaults to the character at x, y.
oldChar = image[y][x]
if oldChar == newChar or image[y][x] != oldChar:
# BASE CASE
return
image[y][x] = newChar # Change the character.
# Uncomment to view each step:
#printImage(image)
# Change the neighboring characters.
if y + 1 < HEIGHT and image[y + 1][x] == oldChar:
# RECURSIVE CASE
floodFill(image, x, y + 1, newChar, oldChar)
if y - 1 >= 0 and image[y - 1][x] == oldChar:
# RECURSIVE CASE
floodFill(image, x, y - 1, newChar, oldChar)
if x + 1 < WIDTH and image[y][x + 1] == oldChar:
# RECURSIVE CASE
floodFill(image, x + 1, y, newChar, oldChar)
if x - 1 >= 0 and image[y][x - 1] == oldChar:
# RECURSIVE CASE
floodFill(image, x - 1, y, newChar, oldChar)
return # BASE CASE
def printImage(image):
for y in range(HEIGHT):
# Print each row.
for x in range(WIDTH):
# Print each column.
sys.stdout.write(image[y][x])
sys.stdout.write('\n')
sys.stdout.write('\n')
printImage(im)
floodFill(im, 3, 3, 'o')
printImage(im)