[英]Python Maze BFS Shortest Path
I am learning searching algorithms and am trying to implement the BFS algorithm to check if a goal is reachable in a maze given a starting position.我正在学习搜索算法并尝试实现 BFS 算法以检查在给定起始 position 的迷宫中是否可以达到目标。 The maze was imported from a txt file as a 2D array.
迷宫是从 txt 文件作为二维数组导入的。 My solution seems to find the goal however I am not able to display just the path that was taken I can only display all the nodes that were visited.
我的解决方案似乎找到了目标,但是我无法仅显示所采用的路径,我只能显示所有访问过的节点。 I would like to display the maze after the algorithm is ran with markers denoting the path that was taken.
我想在算法运行后用表示所走路径的标记来显示迷宫。 Currently displaying indices visited with the "."
当前显示用“。”访问的索引。 symbol.
象征。 The ampersand represents a wall that cannot be passed.
& 符号代表一堵无法通过的墙。 Here is my code:
这是我的代码:
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))
Thank you谢谢
I was able to figure it out.我能够弄清楚。 I had to use a dictionary that stored each called node with the node that called it.
我必须使用一个字典来存储每个被调用节点和调用它的节点。 Afterwards once I got to the goal I looped through each dictionary key value pair starting with my goal as the key to find my path.
之后,一旦我达到目标,我就会遍历每个字典键值对,从我的目标开始作为找到我的路径的关键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.