I have the following recursiv function in python:
def _floodfill(matrix, x, y, counter):
if matrix[x][y] != 9:
matrix[x][y] = 9
counter += 1
# recursively invoke flood fill on all surrounding cells:
if x > 0:
counter += int(_floodfill(matrix, x - 1, y, counter) or 0)
if x < len(matrix) - 1:
counter += int(_floodfill(matrix, x + 1, y, counter) or 0)
if y > 0:
counter += int(_floodfill(matrix, x, y - 1, counter) or 0)
if y < len(matrix[0]) - 1:
counter += int(_floodfill(matrix, x, y + 1, counter) or 0)
return counter
I want to count how often this function is called respectively count how many numbers are != 9 in the region.
Using he following matrix and invocing the function like: _floodfill(matrix,1,1,0) the function should return 2:
[[9,9,9],
[9,2,9],
[9,3,9],
[9,9,9]]
what's the problem with my code?
EDIT I think the function is more readable like this:
def _floodfill(matrix, x, y, counter):
if matrix[x][y] != 9:
matrix[x][y] = 9
counter += 1
# recursively invoke flood fill on all surrounding cells:
if x > 0:
counter += _floodfill(matrix, x - 1, y, counter)
if x < len(matrix) - 1:
counter += _floodfill(matrix, x + 1, y, counter)
if y > 0:
counter += _floodfill(matrix, x, y - 1, counter)
if y < len(matrix[0]) - 1:
counter += _floodfill(matrix, x, y + 1, counter)
return counter
else:
return 0
return counter; then you use this return value in acounter += _floodfill(...). So,counterat least doubles with each recursive call.