1 回答
TA贡献1966条经验 获得超4个赞
您的代码实际上存在几个问题:
您需要指定您的 Djikstra 算法在哪里停止,在您的代码中没有提到什么是结束节点(在您的示例中它应该是 0)
计算成本并
cost = result[len(result) - 1]
不能获得字典中的最后一个元素(字典通常没有排序,因此“最后一个元素”甚至不存在!)。您应该将成本检索为cost = result[end]
,其中end
是最终节点,在您的示例中为 0。您将该函数调用为
result = graph.dijkstra(1, 0, graph.vertexs[2].connections, {}, {node: None for node in graphList})
,但是,该函数的第三个参数应该是初始节点的邻居集,所以它应该graph.vertexs[1].connections
在您的情况下。
综上所述,为了使代码按预期工作,可以对函数进行如下修改:
def dijkstra(self, current, currentDistance, distances, visited, unvisited, end):
for neighbour, distance in distances.items():
if neighbour.name not in unvisited:
continue
newDistance = currentDistance + distance
if unvisited[neighbour.name] is None or unvisited[neighbour.name] > newDistance:
unvisited[neighbour.name] = newDistance
visited[current] = currentDistance
if current == end:
return visited
del unvisited[current]
if not unvisited:
return True
candidates = [node for node in unvisited.items() if node[1]]
current, currentDistance = sorted(candidates)[0]
self.dijkstra(current, currentDistance, graph.vertexs[current].connections, visited, unvisited, end)
return visited
并按如下方式调用它:
print("Shortest possible path from node 1 to 0:")
start = 1
end = 0
result = graph.dijkstra(start, 0, graph.vertexs[start].connections, {}, {node: None for node in graphList}, end)
cost = result[end]
path = " ".join([str(arrInt) for arrInt in list(result.keys())])
print(path, "costing", cost)
通过这样做,输出变为
从节点 1 到 0 的最短路径: 1 6 2 0 成本 15
添加回答
举报