01
—
Dijkstra算法的理论部分
关于Dijkstra算法的原理部分,请参考之前的推送:
图算法|Dijkstra最短路径算法
Dijkstra算法总结如下:
1. 此算法是计算从入度为0的起始点开始的单源最短路径算法,它能计算从源点到图中任何一点的最短路径,假定起始点为A
2. 选取一个中心点center,是S集合中的最后一个元素,注意起始点到这个点的最短距离已经计算出来,并存储在dist字典中了。
3. 因为已经求出了从A->center的最短路径,所以每次迭代只需要找出center->{有关系的节点nodei}的最短距离,如果两者的和小于dist(A->nodei),则找到一条更短的路径。
02
—
代码实现
""" Dijkstra algorithm graphdict={"A":[("B",6),("C",3)], "B":[("C",2),("D",5)],"C":[("B",2),("D",3),("E",4)],\ "D":[("B",5),("C",3),("E",2),("F",3)],"E":[("C",4),("D",2),("F",5)],"F":[("D",3),"(E",5)]}) assert: start node must be zero in-degree """ def Dijkstra(startNode, endNode, graphdict=None): S=[startNode] V=[] for node in graphdict.keys(): if node !=startNode: V.append(node) #distance dict from startNode dist={} for node in V: dist[node]=float('Inf') while len(V)>0: center = S[-1] # get final node for S as the new center node minval = ("None",float("Inf")) for node,d in graphdict[center]: if node not in V: continue #following is the key logic.If S length is bigger than 1,need to get the final ele of S, which is the center point in current #iterator, and distance between start node and center node is startToCenterDist; d is distance between node # among out-degree for center point; dist[node] is previous distance to start node, possibly Inf or a updated value # so if startToCenterDist+d is less than dist[node], then it shows we find a shorter distance. if len(S)==1: dist[node] = d else: startToCenterDist = dist[center] if startToCenterDist + d < dist[node]: dist[node] = startToCenterDist + d #this is the method to find a new center node and # it's the minimum distance among out-degree nodes for center node if d < minval[1]: minval = (node,d) V.remove(minval[0]) S.append(minval[0]) # append node with min val return dist
03
—
测试
求出以上图中,从A到各个节点的最短路径:
shortestRoad = Dijkstra("A","F",graphdict={"A":[("B",6),("C",3)], "B":[("C",2),("D",5)],\
"C":[("B",2),("D",3),("E",4)],\
"D":[("B",5),("C",3),("E",2),("F",3)],\
"E":[("C",4),("D",2),("F",5)],"F":[("D",3),("E",5)]})
mystr = "shortest distance from A begins to "
for key,shortest in shortestRoad.items():
print(mystr+ str(key) +" is: " + str(shortest) )
打印结果如下:
shortest distance from A begins to B is: 5 shortest distance from A begins to C is: 3 shortest distance from A begins to D is: 6 shortest distance from A begins to E is: 7 shortest distance from A begins to F is: 9
本文分享自 程序员郭震zhenguo 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有