您可以使用像propaging这样的前端:
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]
![Final result](https://istack.dev59.com/2M18p.webp)
list_neighbours
中添加对角线距离,然后相应地更新maze_copy
,而不仅仅是相邻的距离。现在这个方法相当简单明了。 - BlueSheepToken