我在Python中实现了基本的线性最短路径算法。根据我遇到的各个网站,这仅适用于有向无环图,包括this,this和this。但是,我不明白为什么会这样。
我甚至用针对具有周期和无方向边的图来测试算法,并且它运行良好。
所以问题是,为什么线性最短路径算法不适用于非定向循环图?边题,这个算法的名称是什么?
作为参考,这是我为算法编写的代码:
def shortestPath(start, end, graph):
# First, topologically sort the graph, to determine which order to traverse it in
sorted = toplogicalSort(start, graph)
# Get ready to store the current weight of each node's path, and their predecessor
weights = [0] + [float('inf')] * (len(graph) - 1)
predecessor = [0] * len(graph)
# Next, relaxes all edges in the order of sorted nodes
for node in sorted:
for neighbour in graph[node]:
# Checks if it would be cheaper to take this path, as opposed to the last path
if weights[neighbour[0]] > weights[node] + neighbour[1]:
# If it is, then adjust the weight and predecessor
weights[neighbour[0]] = weights[node] + neighbour[1]
predecessor[neighbour[0]] = node
# Returns the shortest path to the end
path = [end]
while path[len(path) - 1] != start:
path.append(predecessor[path[len(path) - 1]])
return path[::-1]
编辑:根据Beta的要求,这是拓扑排序:
# Toplogically sorts the graph given, starting from the start point given.
def toplogicalSort(start, graph):
# Runs a DFS on all nodes connected to the starting node in the graph
def DFS(start):
for node in graph[start]:
if not node[0] in checked:
checked[node[0]] = True
DFS(node[0])
finish.append(start)
# Stores the finish point of all nodes in the graph, and a boolean stating if they have been checked
finish, checked = [], {}
DFS(start)
# Reverses the order of the sort, to get a proper topology; then returns
return finish[::-1]
答案 0 :(得分:3)
因为你不能在拓扑上对带有周期的图形进行排序(因此,无法确定哪个节点应该先于另一个节点,因此无向图也是不可能的。)
编辑:阅读完评论后,我认为这实际上就是@Beta的含义。
答案 1 :(得分:0)
当存在周期时,拓扑排序不能保证最短路径的正确排序。
例如,我们有一个图表:
A->C, A->B, B->C, C->B, B->D
说正确的最短路径是:
A->C->B->D
但拓扑排序可以生成订单:
A->B->C->D
虽然在访问B
时会将C
更新为正确的顺序,但B
不会再次访问,因此无法将正确的权重传播到{{1} }}。 (虽然路径恰好是正确的。)