Reputation: 31
I need to write a flood fill algorithm to be used in a larger code that fills specific cells of a cave with different colors of water based on which room they are in.
For some reason my recursive algorithm isn't working and keeps telling me I'm exceeding the maximum recursion depth, and I have no clue why.
I'm trying to go cell by cell, checking if it is AIR, STONE, or WATER, and if it is STONE or WATER I want it to do nothing. If it is AIR, I want it to fill that cell.
Can anyone give me some tips or advice?
#flood fill algorithm
def fill(cave, row, col, color):
caveWidth = len(cave)
caveHeigth = len(cave[0])
if row > 0:
fill(cave, row-1, col, color) #left
if col > 0:
fill(cave, row, col-1, color) #up
if row < caveWidth-1:
fill(cave, row+1, col, color) #right
if col < caveHeigth-1:
fill(cave, row, col+1, color) #down
if cave[row][col] == STONE or cave[row][col] == WATER:
return
if cave[row][col] == AIR :
cave[row][col] = WATER
grid.fill_cell(row, col, color)
Upvotes: 3
Views: 1860
Reputation: 11532
Don't use recursive algorithms, they are the devil's playthings.
The wikipedia lists various practical algorithms like scanline fill.
Upvotes: 1
Reputation: 25454
Print row
and col
at the start of the fill
routine to see what's wrong here. A little code reordering and you're fine :-)
Upvotes: 5