您可以使用正在传播的前端,例如:
import matplotlib.pyplot as plt
def cond(x, y, max_x, max_y, maze):
return 0 <= x < max_x and 0 <= y < max_y and maze[y][x] == 0
def neighbours(point, maze):
max_x = len(maze[0])
max_y = len(maze)
x = point[0]
y = point[1]
list_neighbours = [(i, y) for i in (x - 1, x + 1) if cond(i, y, max_x, max_y, maze)] \
+ [(x, j) for j in (y - 1, y + 1) if cond(x, j, max_x, max_y, maze)]
return list_neighbours
maze = [
[0, 0, 1, 1],
[0, 1, 1, 0],
[0, 0, 0, 0],
[0, 0, 1, 0]
]
start = (0, 0)
maze_copy = [[-1] * len(maze[0]) for _ in range(len(maze))]
front = [(0, 0)]
step = 0
while front:
new_front = []
for point in front:
new_front += [p for p in neighbours(point, maze) if maze_copy[p[1]][p[0]] == -1]
maze_copy[point[1]][point[0]] = step
step += 1
front = list(set(new_front))
print(maze_copy)
plt.imshow(maze_copy, cmap='hot', interpolation='nearest')
plt.show()
在代码中,1
代表墙壁和可0
穿越的部分。我制作了迷宫的副本以跟踪已经访问过的像素。
这个想法是有一个可以传播和填充maze_copy
.
这导致以下填充:
[0, -1, -1, -1]
[-1, -1, -1, -1]
[-1, -1, -1, -1]
[-1, -1, -1, -1]
[0, 1, -1, -1]
[1, -1, -1, -1]
[-1, -1, -1, -1]
[-1, -1, -1, -1]
[0, 1, -1, -1]
[1, -1, -1, -1]
[2, -1, -1, -1]
[-1, -1, -1, -1]
[0, 1, -1, -1]
[1, -1, -1, -1]
[2, 3, -1, -1]
[3, -1, -1, -1]
[0, 1, -1, -1]
[1, -1, -1, -1]
[2, 3, 4, -1]
[3, 4, -1, -1]
[0, 1, -1, -1]
[1, -1, -1, -1]
[2, 3, 4, 5]
[3, 4, -1, -1]
[0, 1, -1, -1]
[1, -1, -1, 6]
[2, 3, 4, 5]
[3, 4, -1, 6]
