【发布时间】:2015-04-01 09:56:24
【问题描述】:
我想在带有 bfs 的图中找到两个节点之间的路径。我编写了一个以正确顺序访问所有节点的函数(不确定它是否有效,但对我来说似乎是正确的)但我需要存储路径(包含构成路径的所有边的列表),但我没有不知道怎么做:\
有人可以帮助我吗?在此先感谢:)
【问题讨论】:
标签: java graph path breadth-first-search
我想在带有 bfs 的图中找到两个节点之间的路径。我编写了一个以正确顺序访问所有节点的函数(不确定它是否有效,但对我来说似乎是正确的)但我需要存储路径(包含构成路径的所有边的列表),但我没有不知道怎么做:\
有人可以帮助我吗?在此先感谢:)
【问题讨论】:
标签: java graph path breadth-first-search
您创建了一个数组pof parents。所以如果p[u] = v 在从源到u 的路径中有一条从v 到u 的边。其中源顶点的父节点是null。
因此,当我们在当前顶点v 中时,在将其相邻顶点u 插入队列之前,我们生成p[w] = v。当您找到目标顶点时,您会在数组 p 中向后退。从目标顶点w开始,p[w]是w的父级,p[p[w]]是w的父级的父级,以此类推。
【讨论】:
这可能是其中一种方法。
在这种方法中,您保留一个列表队列,您可以在其中获取列表并从该列表中获取第一个节点。
找到该节点的adj(),并为每个未访问的节点在队列中添加一个新的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
我希望这会有所帮助。
【讨论】: