如何解决使用 heapq 为 dijkstra 最短路径算法列出可用的最短路径
我接到了一项任务,需要在我的 Python 代码中应用 Dijkstra 的最短路径算法。假设我们有几个城市参与。我需要找到路线最短的那个。总之,任务是:
- 找出最短路线。
- 列出所有可能的路径。
我成功地找到了城市之间的最短路径,但我不知道如何使用 heapq 列出所有可能的路径。有人可以帮我吗?
这是我为了更好地理解图表而提供的图表:
代码:
import heapq
from collections import defaultdict
global shortestPath
global shortestCost
shortestPath = "null"
shortestCost = 100000
def dijkstra(graph,src,dest):
h = []
heapq.heappush(h,(0,src))
global shortestPath
global shortestCost
global source
while len(h)!=0:
currcost,currvtx = heapq.heappop(h)
if currvtx == dest:
print("\t\t\t{} to {} with cost {}".format(src,dest,currcost))
if currcost < shortestCost:
if dest == src:
continue
else:
shortestCost = currcost
shortestPath = dest
break
for neigh,neighcost in graph[currvtx]:
heapq.heappush(h,(currcost+neighcost,neigh))
city = ["A","B","C","D","E","F"]
graph = defaultdict(list)
graph["A"] = [("B",1),("C",5)]
graph["B"] = [('C',6),('D',23)]
graph["C"] = [('E',35)]
graph["D"] = [('F',26)]
graph["E"] = [('D',54)]
print ("\t=============================================================================")
print ("\t Dijkstra's Shortest Path Algorithm")
print ("\t=============================================================================")
print ("\n\tAssume 1 cost = 10 km")
print ("\n\tCity availability: {} ".format(city))
src = "A"
print ("\n\tPossible paths from {} :\n".format(src))
for i in city:
dijkstra(graph,i)
print ("\n\t=============================================================================")
print("\t\tThe shortest path from {} is {} to {} with cost {}".format(src,shortestPath,shortestCost))
print ("\t=============================================================================")
输出:
=============================================================================
Dijkstra's Shortest Path Algorithm
=============================================================================
Assume 1 cost = 10 km
City availability: ['A','B','C','D','E','F']
Possible paths from A :
A to A with cost 0
A to B with cost 1
A to C with cost 5
A to D with cost 24
A to E with cost 40
A to F with cost 50
=============================================================================
The shortest path from A is A to B with cost 1
=============================================================================
如果这篇文章看起来不合适,我很抱歉,因为这是我在这里发布的第一个问题。
非常感谢您的帮助。谢谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。