【发布时间】:2023-01-28 06:09:56
【问题描述】:
我正在尝试编写一种算法来构建迷宫(请参阅优秀书籍“程序员的迷宫”)。 我正在尝试实现 aldous-broder 算法。 我下面的 while 循环永远持续下去,我不明白为什么。 基本上,它是 Cell 类(程序中较早创建的类)对象之间的随机游走。我们在进入循环之前初始化一个“actual_cell”,我们在可能的邻居中随机选择一个邻居,我们应用“dig”函数(挖掘两个 Cell 对象之间的墙),我们减少访问的单元格的数量并替换 actual_cell by neighbor 迭代 while 循环,直到访问了所有单元格。 该错误似乎发生在 actual_cell = neighbour 行,这是触发下一轮所必需的。 actual_cell 和 neighbor 都属于 Cell 类。
def aldous_broder(Grid):
actual_cell = random.choice(Grid.cells)
not_yet_visited = len(Grid.cells)-1
while not_yet_visited > 0:
neighbors = []
if actual_cell.north_cell is not None:
neighbors.append(actual_cell.north_cell)
if actual_cell.east_cell is not None:
neighbors.append(actual_cell.east_cell)
if actual_cell.south_cell is not None:
neighbors.append(actual_cell.south_cell)
if actual_cell.west_cell is not None:
neighbors.append(actual_cell.west_cell)
if neighbors:
neighbor = random.choice(neighbors)
if not neighbor.links: #If list is not empty (empty = False)
actual_cell.dig(neighbor, bidirectional = True)
not_yet_visited -= 1
actual_cell = neighbor
【问题讨论】:
-
在调试器下运行它并观察行为。
-
你能保证有一个
neighbor吗?现在,如果你没有遇到任何邻居,你就会被困在那个牢房里。如果你没有遇到邻居,你需要一种回溯的方法。 -
我会看看调试器,谢谢你的建议。事实上,我有一个邻居(Cell 类),我可以用 print 和 print(type(neighbor)) 检查它,减量也有效,但仅适用于 loop1。递减后似乎卡住了:/
标签: python while-loop