当前位置: 移动技术网 > IT编程>脚本编程>Python > 狄克斯拉特算法。 适用于,加权有向无环图,且无负权边,的最短路径计算。

狄克斯拉特算法。 适用于,加权有向无环图,且无负权边,的最短路径计算。

2018年10月24日  | 移动技术网IT编程  | 我要评论

蛮童之歌,爸爸去哪儿什么时候更新,q宠迷你小保姆

没事时看的一道题,解完后发现这居然是一个算法。

就在这里拷贝一份,免得后面自己都忘了自己原来写的是什么东西。

核心思路:

1、找到临近节点中路径最短的那一个。

2、更新从该节点去它临近节点的,到达临近节点所用的路径。(到新节点的路径比原路径短,才更新)

3、重复这个过程,直到对应的图中所有的节点都试过了。

4、计算最终路径。

 

def find_lowest_cost(costs,process):
lower_k = none
for cost_k in costs:
if cost_k not in process:
lower_k = cost_k
return lower_k
# 总字典,反正我是这么叫的
graps = dict()
graps['star'] = {'a':6,'b':2}
graps['a'] = {'end':1}
graps['b'] = {'a':3,"end":5}
graps['end'] = dict()
print(graps)
# 无穷大
infinity = float("inf")
# 父字典,开销字典
costs = dict()
costs['a'] = 6
costs['b'] = 2
costs['end'] = infinity
print(costs)
parent = dict()
parent['a'] = 'star'
parent['b'] = 'star'
parent['end'] = none
print(parent)
# 储存已经处理节点
process = []
print('华丽的分割线'.center(50,'-'))
while 1:
lowest_k = find_lowest_cost(costs, process)
if lowest_k == none:
break
for k in graps[lowest_k]:
if graps[lowest_k][k] + costs[lowest_k] < costs[k]:
costs[k] = graps[lowest_k][k] + costs[lowest_k]
parent[k] = lowest_k
process.append(lowest_k)
print('costs: ', costs)
print('parent: ', parent)
print("procrss: ", process)

aaaaaaa,我的代码就是这么难看。反正是给我自己看的。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网