为什么FloodFill算法超过Leetcode的最大递归限制?

2024-09-29 01:21:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用与非常流行的岛屿数问题相同的逻辑来研究泛洪填充算法。所以当我用示例输入运行代码时,这个解决方案是有效的,但是一旦我提交,它就会显示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)

Tags: 算法示例lenreturnifdef逻辑grid
1条回答
网友
1楼 · 发布于 2024-09-29 01:21:45

我相信代码是好的情况下,新的颜色!=og。但是我猜您看到了错误,因为在newColor==og的情况下,停止条件

if grid[sr][sc]!= og:
        return

不会发生,导致recurse无休止地递归。只需在floodfill方法中为这种边缘情况添加一个检查,就可以解决这个问题。你知道吗

相关问题 更多 >