-
Notifications
You must be signed in to change notification settings - Fork 2
/
RecursiveFloodFill.py
69 lines (59 loc) · 1.4 KB
/
RecursiveFloodFill.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
57
58
59
60
61
62
63
64
65
66
67
68
69
import sys
textmap = """
....................
.......XXXXXXXXXX...
.......X........X...
.......X........X...
..XXXXXX........X...
..X.............X...
..X.............X...
..X........XXXXXX...
..X........X........
..XXXX..XXXX........
.....XXXX...........
....................
....................
"""
lines = textmap.strip().split('\n')
height = len(lines)
width = len(lines[0])
def getWorldFromText():
world = []
for x in xrange(width):
world.append([''] * height)
for x in xrange(width):
for y in xrange(height):
world[x][y] = lines[y][x]
return world
def printWorld(world):
for x in xrange(height):
for y in xrange(width):
sys.stdout.write(world[y][x])
print
def fillWorld(world, x, y, oldCharacter, newCharacter):
if oldCharacter == None:
oldCharacter = world[x][y]
if oldCharacter != world[x][y]:
return
world[x][y] = newCharacter
if x > 0:
fillWorld(world, x-1, y, oldCharacter, newCharacter) # left
if x < width -1:
fillWorld(world, x+1, y, oldCharacter, newCharacter) # right
if y > 0:
fillWorld(world, x, y-1, oldCharacter, newCharacter) # up
if y < height - 1:
fillWorld(world, x, y+1, oldCharacter, newCharacter) # down
return world
def main():
world = getWorldFromText()
printWorld(world)
print
world = fillWorld(world, 5, 8, None, '+')
printWorld(world)
print
world = fillWorld(world, 0, 0, None, 's')
printWorld(world)
print
if __name__ == '__main__':
main()