首页 > 编程语言 > 详细

迪克斯特拉算法python实现

时间:2018-09-11 23:18:58      阅读:234      评论:0      收藏:0      [点我收藏+]
graph={}
graph[‘start‘]={} #定义图中的各个邻居节点
graph[‘start‘][‘a‘]=6
graph[‘start‘][‘b‘]=-1
graph[‘a‘]={}
graph[‘a‘][‘end‘]=1
graph[‘b‘]={}
graph[‘b‘][‘a‘]=3
graph[‘b‘][‘end‘]=5
graph[‘end‘]={}
cost={} #首尾已知点的代价
infinity=float(‘inf‘)
cost[‘a‘]=6
cost[‘b‘]=-1
cost[‘end‘]=infinity
parent={} #首尾已知点的负节点
parent[‘a‘]=‘start‘
parent[‘b‘]=‘start‘
parent[‘end‘]=None
#print(cost.keys())
process=[]
def select_lowest_cost(cost):
lowest_cost=float(‘inf‘)
lowest_cost_node=None
for node in cost.keys() :
if cost[node]<lowest_cost and node not in process: #保证所有的初始节点(第一步)都被考虑到
lowest_cost=cost[node]
lowest_cost_node=node
return lowest_cost_node
#print(select_lowest_cost(cost))
node=select_lowest_cost(cost)
while node is not None:
neighbor=graph[node]
costs=cost[node]
#neighbor[node]=graph[node].keys()
for i in neighbor.keys():
c=costs+neighbor[i]
if c<cost[i]:
cost[i]=c
parent[i]=node
process.append(node) #处理完的点表示该节点所有的邻居节点都考虑完全
node = select_lowest_cost(cost)
print(cost[‘end‘])


迪克斯特拉算法python实现

原文:https://www.cnblogs.com/masterhu/p/9631098.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!