【问题标题】:while loop infinite in random walk algorithm随机游走算法中的 while 循环无限
【发布时间】: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


【解决方案1】:

非常感谢@Michael Cao,你是对的。问题是所有 actual_cell 都是“无”,这会损害循环。我修复了分配以避免无,错误消失了:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多