使用 heapq 为 dijkstra 最短路径算法列出可用的最短路径

问题描述

我接到了一项任务,需要在我的 Python 代码中应用 Dijkstra 的最短路径算法。假设我们有几个城市参与。我需要找到路线最短的那个。总之,任务是:

  • 找出最短路线。
  • 列出所有可能的路径。

我成功地找到了城市之间的最短路径,但我不知道如何使用 heapq 列出所有可能的路径。有人可以帮我吗?

这是我为了更好地理解图表而提供的图表:

The graph that I construct

代码

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 (将#修改为@)