繁体   English   中英

在图中使用BFS查找路径

[英]Find a path with BFS in a graph

我想在具有bfs的图中找到两个节点之间的路径。 我编写了一个函数,以正确的顺序访问所有节点(不确定它是否有效,但对我而言似乎正确),但是我需要存储路径(包含构成路径的所有边的列表),而我没有不知道该怎么做:\\

有人能帮我吗 ? 提前致谢 :)

您创建一个父项数组p 因此,如果p[u] = v ,则从源到u的路径中有一个从vu的边。 其中源顶点的父级为null

因此,当我们在当前顶点v ,在将其相邻顶点u插入队列之前,我们使p[w] = v 找到目标顶点后,您将在数组p中向后移动。 从目标顶点开始wp[w]时的父wp[p[w]]是父的父w等。

这可以是方法之一。

通过这种方法,您可以将列表排队,从中获得列表并从该列表中获取第一个节点。

找到该节点的adj() ,并为每个未访问的path+[node]在队列中添加一个新的path+[node] ,如果到达目的地,则返回该path+[node]

step 1 : create a queue of to hold the paths.
step 2 : add the source as  [ source ] in the queue
step 3 : while the queue is not empty get one path from it
         (as this works for both bfs and dfs thats why "get" not "dequeue" or "pop")

step 4: get the last node of that path (list)
step 5: get the adj of that node and for each not explored create a new path i.e oldpath +[adj node]

step 6:if the adj node is what u want then return the path else add the path to the queue

我希望这可以帮到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM