我有一张图,想要找到两个节点之间的所有最短路径。我已经通过BFS找到了两个节点之间的一条最短路径。但是,如果存在多条最短路径,则只给出其中一条。
如何使用BFS获取所有最短路径?
我已经按照众所周知的BFS伪代码实现了我的代码。此外,我有一个邻接列表向量,它保存了所有节点的邻接顶点。
我有一张图,想要找到两个节点之间的所有最短路径。我已经通过BFS找到了两个节点之间的一条最短路径。但是,如果存在多条最短路径,则只给出其中一条。
如何使用BFS获取所有最短路径?
我已经按照众所周知的BFS伪代码实现了我的代码。此外,我有一个邻接列表向量,它保存了所有节点的邻接顶点。
您可以通过为每个节点维护一个父节点列表或向量来轻松完成此操作。如果两个或多个距离起始节点相同的节点(例如X,Y,Z)通向另一个节点M,则将所有X,Y和Z作为M的父节点。
您只需添加一个检查,以查看在将父节点添加到节点时,该父节点是否与先前的父节点处于同一级别。
通过级别,我指的是距离起点的距离。
这样,您就可以通过回溯父节点向量来获取所有最短路径。以下是我的C++实现。
我希望您知道如何从目标开始打印路径,跟踪父节点并到达起点。
编辑:伪代码
bfs (start , end)
enqueue(start)
visited[start] = 1
while queue is NOT empty
currentNode = queue.front()
dequeue()
if(currentNode == end)
break
for each node adjacent to currentNode
if node is unvisited
visited[node] = visited[curr] + 1
enqueue(node)
parent[node].add(currentNode)
else if(currentNode is in same level as node's parents)
parent[node].add(currentNode)
return
如果图形很大,从起点到终点找到所有路径,然后选择最短的路径可能非常低效。这里有一个更好的算法:
Using BFS, label each node with its distance from the start node. Stop when you get to the end node.
def bfs_label(start, end):
depth = {start: 0}
nodes = [start]
while nodes:
next_nodes = []
for node in nodes:
if node == end:
return depth
for neighbor in neighbors(node):
if neighbor not in depth:
depth[neighbor] = depth[node] + 1
fringe.append(neighbor)
Using DFS, find all paths from the start node to the end node such that the depth strictly increases for each step of the path.
def shortest_paths(node, end, depth, path=None):
if path is None:
path = []
path.append(node)
if node == end:
yield tuple(path)
else:
for neighbor in neighbors(node):
if neighbor in depth and depth[neighbor] == depth[node]+1:
for sp in shortest_paths(neighbor, end, depth, path):
yield sp
path.pop()
dfs(p,len)
if(visited[p])
return
if(p== destination)
paths.append(len)
return
visited[p]=1
for each w adjacent to p
dfs(w,len+1)
visited[p]=0
你可以通过维护一个路径数组来找到路径。我会把这个留给你作为一个任务。
1
,它首先会到达2
,并找到1->2->3->4
,然后回溯回到1
,再到3
并找到1->3->4
。而您的重复评论可能更适合作为问题的评论或重复标记(我刚刚已经标记了它)。 - Bernhard Barker