洪水填充蟒蛇,解决迷宫

时间:2014-04-09 20:54:55

标签: python-2.7 flood-fill

返回索引超出范围错误,有人请帮忙!

def floodfill(maze, x, y, a, b):
    #maze[x][y] = b
    for i in range(1,len(maze)):
        for j in range(len(maze[i])):
            if maze[i-1][j] == a or [i][j-1] == a or maze[i-1][j] == b or maze[i][j-1] == b:
                if maze[i][j] == a:
                    maze[i][j] = b
    return maze

这里是正在解决的“迷宫”......洪水填充应该将所有0改为1

[[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], 
 [0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -1], 
 [-1, 0, -1, -1, -1, 0, -1, 0, -1, 0, -1], 
 [-1, 0, -1, 0, 0, 0, -1, 0, -1, 0, -1], 
 [-1, 0, -1, -1, -1, -1, -1, 0, -1, 0, -1], 
 [-1, 0, 0, 0, 0, 0, 0, 0, -1, 0, -1], 
 [-1, 0, -1, -1, -1, -1, -1, -1, -1, 0, -1], 
 [-1, 0, -1, 0, 0, 0, 0, 0, 0, 0, -1], 
 [-1, 0, -1, -1, -1, -1, -1, -1, -1, 0, -1], 
 [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
 [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]]

1 个答案:

答案 0 :(得分:2)

在代码的第5行,在第一个or中,它只是单独说[i][j-1]

>>> i = 9
>>> j = 10
>>> [i][j-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> 

您正在尝试获取整数j-1的{​​{1}} th 值,这显然不起作用:)。

只需将i放在这两个之前即可:maze