【发布时间】:2018-09-08 05:24:19
【问题描述】:
我一直在寻找在 python 中创建迷宫的方法。
我在rosettacode 遇到了下面的代码。
我知道代码使用递归来构建迷宫。
我了解代码行并且知道我在阅读什么,并且我想使用该代码,但我缺少对该代码的关键理解。
这段代码中的递归函数究竟是如何知道何时停止的?
from random import shuffle, randrange
def make_maze(w = 16, h = 8):
vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]
ver = [["| "] * w + ['|'] for _ in range(h)] + [[]]
hor = [["+--"] * w + ['+'] for _ in range(h + 1)]
def walk(x, y):
vis[y][x] = 1
d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]
shuffle(d)
for (xx, yy) in d:
if vis[yy][xx]: continue
if xx == x: hor[max(y, yy)][x] = "+ "
if yy == y: ver[y][max(x, xx)] = " "
walk(xx, yy)
walk(randrange(w), randrange(h))
s = ""
for (a, b) in zip(hor, ver):
s += ''.join(a + ['\n'] + b + ['\n'])
return s
if __name__ == '__main__':
print(make_maze())
【问题讨论】:
-
滚动到您引用的页面顶部:
Start at a random cell. Mark the current cell as visited, and get a list of its neighbors. For each neighbor, starting with a randomly selected neighbor: If that neighbor hasn't been visited, remove the wall between this cell and that neighbor, and then recurse with that neighbor as the current cell.- 当所有邻居都被访问时,它会停止。 -
如果您将尺寸更改为 2 和 3 并注意How to debug small programs (#2),您可以自己调试它的工作...
标签: python python-3.x recursion depth-first-search backtracking