【发布时间】:2022-01-14 13:22:32
【问题描述】:
我在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
我想计算这个函数被调用的频率,分别计算该区域中有多少个数字!= 9。
使用下面的矩阵并调用函数,如:_floodfill(matrix,1,1,0) 该函数应返回 2:
[[9,9,9],
[9,2,9],
[9,3,9],
[9,9,9]]
我的代码有什么问题?
编辑 我认为这个函数更具可读性:
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;然后你在counter += _floodfill(...)中使用这个返回值。所以,counter每次递归调用至少翻倍。