递归算法洪水填充

时间:2015-01-23 23:53:55

标签: python python-3.x recursion flood-fill

每次运行此操作时都会出现堆栈溢出,我知道这是因为算法永远不会达到基本情况。我也知道在这种情况下最好使用迭代,但这必须以递归方式完成。任何提示,技巧或建议,如何使它不溢出,仍然执行它所需要的是非常感谢。

def fill(cave, row, col, color):
    """Fill a chamber of the cave with water, starting
    at row, col. Water can spread in all four cardinal
    directions, but cannot penetrate stone.  No effect
    if row or col are not inside the cave.

    Attempting to pour water where there is already WATER or STONE
    has no effect.  Attempting to pour water outside the cavern has
    no effect.  Attempting to pour water in a cell containing AIR 
    not only places colored water in that cell, but also spreads it
    in all directions by causing it to be poured in the cell to the 
    left and right and above and below. 

    Args: 
        cave: A matrix (list of lists) representing the cavern. Each 
            cell in the cave may hold AIR, STONE, or WATER.
        row: Starting row of the grid cell where we pour water
        col: Starting column of the grid cell where we pour water
        color: color of the water we try to pour in.
    """
    caveWidth = len(cave)
    caveHeigth = len(cave[0])

    if cave[row][col] == STONE or cave[row][col] == WATER:
        return

    if row > 0:
        fill(cave, row-1, col, color) #left
    if row < caveWidth-1:
        fill(cave, row+1, col, color) #right
    if col > 0:
        fill(cave, row, col-1, color) #up
    if col < caveHeigth-1:
        fill(cave, row+1, col, color) #down

    if cave[row][col] == AIR :
        cave[row][col] = WATER
        grid.fill_cell(row, col, color)

1 个答案:

答案 0 :(得分:1)

在进行递归调用之前,将当前单元格设置为WATER 。否则它可以无限地在两个相邻的AIR单元上反弹。

if cave[row][col] == AIR :
        cave[row][col] = WATER
        grid.fill_cell(row, col, color)

if row > 0:
        fill(cave, row-1, col, color) #left
    if row < caveWidth-1:
        fill(cave, row+1, col, color) #right
    if col > 0:
        fill(cave, row, col-1, color) #up
    if col < caveHeigth-1:
        fill(cave, row+1, col, color) #down