1. 程式人生 > >狄克斯拉特算法。 適用於,加權有向無環圖,且無負權邊,的最短路徑計算。

狄克斯拉特算法。 適用於,加權有向無環圖,且無負權邊,的最短路徑計算。

app 計算 aaaaaa ict nbsp aps ces find aaaaa

沒事時看的一道題,解完後發現這居然是一個算法。

就在這裏拷貝一份,免得後面自己都忘了自己原來寫的是什麽東西。

核心思路:

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,我的代碼就是這麽難看。反正是給我自己看的。

狄克斯拉特算法。 適用於,加權有向無環圖,且無負權邊,的最短路徑計算。