我正在使用与非常流行的岛屿数问题相同的逻辑来研究泛洪填充算法。所以当我用示例输入运行代码时,这个解决方案是有效的,但是一旦我提交,它就会显示Recursion Error: maximum recursion depth exceeded in comparison
。你知道吗
我怎样才能做得更好?我觉得很好,但我知道有点不对劲。你知道吗
def floodfill(grid,sr,sc,newColor):
og= grid[sr][sc]
recurse(grid,sr,sc,newColor,og)
return grid
def recurse(grid,sr,sc,newColor,og):
if grid[sr][sc]!= og:
return
grid[sr][sc] = newColor
if sr !=0:
recurse(grid,sr-1,sc,newColor,og)
if sc !=0:
recurse(grid,sr,sc-1,newColor,og)
if sc != len(grid[0])-1:
recurse(grid,sr,sc+1,newColor,og)
if sr != len(grid)-1:
recurse(grid,sr+1,sc,newColor,og)
floodfill([[1,1,1],[1,1,0],[1,0,1]],1,1,2)
我相信代码是好的情况下,新的颜色!=og。但是我猜您看到了错误,因为在newColor==og的情况下,停止条件
不会发生,导致
recurse
无休止地递归。只需在floodfill
方法中为这种边缘情况添加一个检查,就可以解决这个问题。你知道吗相关问题 更多 >
编程相关推荐