【问题标题】:Python Maze BFS Shortest PathPython Maze BFS 最短路径
【发布时间】:2019-11-04 06:35:25
【问题描述】:

我正在学习搜索算法并尝试实施 BFS 算法来检查在给定起始位置的迷宫中是否可以达到目标。迷宫是从 txt 文件作为二维数组导入的。我的解决方案似乎找到了目标,但是我无法仅显示所采用的路径,我只能显示访问过的所有节点。我想在算法运行后显示迷宫,并使用表示所走路径的标记。当前显示用“。”访问的索引。象征。与号代表一堵无法通过的墙。这是我的代码:

def BFS(maze, start, goal):

queue = deque([start])

visited = set(([start]))

while(queue):

    x, y = queue.popleft()

    if ((x,y) == goal):
        return x

    if (start != (x,y)):
        maze[x][y] = '.'

    visited.add((x,y))

    if (maze[x][y+1] != "&" and (x,y+1) not in visited):
        queue.append((x,y+1))

    if (maze[x][y-1] != "&" and (x,y-1) not in visited):
        queue.append((x,y-1))

    if (maze[x-1][y] != "&" and (x-1,y) not in visited):
        queue.append((x-1,y)) 

    if (maze[x+1][y] != "&" and (x+1,y) not in visited):
        queue.append((x+1,y)) 

谢谢

【问题讨论】:

    标签: python algorithm path breadth-first-search maze


    【解决方案1】:

    我能够弄清楚。我必须使用一个字典来存储每个被调用节点和调用它的节点。之后,一旦我到达目标,我就会循环遍历每个字典键值对,从我的目标开始作为找到我的路径的键。

    【讨论】:

    • 如果您能分享二维数组以更好地理解它,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多