gpt4 book ai didi

algorithm - 如何找到无向图中从s(任意起始顶点)到v(任意顶点)的最短路径是否唯一?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:48:00 26 4
gpt4 key购买 nike

给定一个没有负权重的无向图 G = (V, E)。检查给定图中每个顶点的最短路径的唯一性的复杂性是多少?

最佳答案

您也可以轻松地修改最短路径算法以找到最短路径的数量。例如考虑这个 Dijkstra 代码:

def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
dist[source] = 0
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))

while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]: # Relax (u,v,a)
dist[v] = alt
previous[v] = u

我们添加另一个列表来存储到每个节点的最短路径的数量。

num_path = {vertex: 0 for vertex in self.vertices}

然后在放松阶段,我们不再检查新距离 (alt) 是否小于之前的距离,而是检查它是否也相等。如果相等,我们增加该节点的最短路径数:

if alt == dist[v]:
num_path[v] += 1

当我们为一个节点找到新的最短路径时,新节点的最短路径数等于其父节点的最短路径数:

if alt < distance:
num_path[v] = num_path[u]
...

所以最后如果 num_path[v]==1 那么我们可以得出结论,从 sourcev 存在唯一的最短路径>.

这是最终代码:

def dijkstra(self, source, dest):
assert source in self.vertices
dist = {vertex: inf for vertex in self.vertices}
previous = {vertex: None for vertex in self.vertices}
num_path = {vertex: 0 for vertex in self.vertices}
dist[source] = 0
num_path[source] = 1
q = self.vertices.copy()
neighbours = {vertex: set() for vertex in self.vertices}
for start, end, cost in self.edges:
neighbours[start].add((end, cost))

while q:
u = min(q, key=lambda vertex: dist[vertex])
q.remove(u)
if dist[u] == inf or u == dest:
break
for v, cost in neighbours[u]:
alt = dist[u] + cost
if alt < dist[v]: # Relax (u,v,a)
dist[v] = alt
previous[v] = u
num_path[v] = num_path[u]
elif alt == dist[v]:
num_path[v] += 1

所以复杂度将等于您的最短路径算法的复杂度。

关于algorithm - 如何找到无向图中从s(任意起始顶点)到v(任意顶点)的最短路径是否唯一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40049959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com