码迷,mamicode.com
首页 > 编程语言 > 详细

迪克斯特拉算法python实现

时间:2018-09-11 23:55:04      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:not   for   parent   start   color   span   pre   ret   sel   

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实现

标签:not   for   parent   start   color   span   pre   ret   sel   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!