演算法學習筆記--狄克斯特拉演算法
阿新 • • 發佈:2018-12-30
演算法學習筆記–狄克斯特拉演算法
主要內容
- 加權圖:提高或降低某些邊的權重
- 介紹狄克斯特拉演算法,能找出加權圖中前往X的最短路徑
- 圖中的環會導致狄克斯特拉演算法不管用,如果有負權重也不適用
如果要處理負權重的圖,可以使用貝爾曼-福德演算法
狄克斯特演算法的四個步驟
- 找出最便宜的節點,即可在最短時間內到達的節點
- 對於該節點的鄰居,檢查是否有前往它們的更短路徑,如果有,就更新其開銷。
- 重複這個過程,直到對圖中的每個節點都這樣做了。就是對每個節點都做,做完一個扔掉一個。
計算最終路徑。
對於狄克斯特演算法計算的時候畫一個表格,三列分別為父節點,節點和開銷,最短的路徑是多少看最後的開銷,最短的路徑沿著父節點回溯。
幾個定義
邊帶權重的圖稱為加權圖,不帶權重的稱為非加權圖。計算非加權圖的最短路徑使用廣度優先搜尋。
繞環的路徑不可能是最短的路徑。
繞環圖就等於無向圖
狄克斯特只適用與有向無環圖
實現
需要三個散列表,並且graph圖列表是巢狀的散列表
1. graph散列表
2. costs開銷散列表
3. parents父節點散列表
def find_lowest_cost_node(costs):
lowest_cost = float('inf')
lowest_cost_node = None
for node in costs:
cost = costs[node]
if cost < lowest_cost and node not in processed:
lowest_cost = cost
lowest_cost_node = node
return lowest_cost_node
if __name__ == '__main__':
graph = {}
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
graph['a'] = {}
graph['a' ]['fin'] = 1
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['fin'] = 5
graph['fin'] = {}
infinity = float("inf")
costs = {}
costs['a'] = 6
costs['b'] = 2
costs["fin"] = infinity
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None
processed = []
node = find_lowest_cost_node(costs)
while node is not None:
cost = costs[node]
neighbors = graph[node]
for n in neighbors.keys():
new_cost = cost + neighbors[n]
if costs[n] > new_cost:
costs[n] = new_cost
parents[n] = node
processed.append(node)
node = find_lowest_cost_node(costs)
print costs['fin']