《算法圖解》第七章筆記_迪傑斯特拉算法


軟件環境:Python 3.7.0b4

一、迪傑斯特拉(dijkstras)算法介紹

算法目標:找出一個圖中最快(耗時最短)的路徑。

實現步驟:

  1. 找出最短時間內前往的節點;
  2. 對於該節點的鄰居,檢查是否有前往它們的更短路徑,如果有,就更新其開銷;
  3. 重復這個過程,直到對圖中的每個節點都重復了以上兩個步驟;
  4. 計算最終路徑。

 

二、迪傑斯特拉算法術語介紹

迪傑斯特拉算法用於每條邊都有關聯數字的圖,這些數字稱為權重(weight)。

帶權重的圖稱為加權圖(weighted graph),不帶權重的圖稱為非加權圖(unweighted graph)

要計算非加權圖中的最短路徑,可使用廣度優先搜索。要計算加權圖中的最短路徑,可使用狄克斯特拉算法。

 

三、算法實現

以下圖為例

要解決這個問題,需要先畫出三個散列表:

隨着算法的進行,我們將不斷更新散列表costs和parents。

graph = {}  #首先需要實現這個圖

 

需要同時存儲鄰居和前往鄰居的開銷

graph["start"] = {}
graph["start"]["a"] = 6
graph["start"]["b"] = 2

    

同時還需要用一個散列表來存儲每個節點的開銷,一個存儲父節點的散列表,一個數組。

下面來看看算法的執行過程:

完整代碼如下(Python)

# 添加節點和鄰居
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 = []  # 一個數組,用於記錄處理過的節點。因為對於同一個節點,不用處理多次。

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

# 在未處理的節點中找出開銷最小的節點
node = find_lowest_cost_node(costs)
# 這個while循環在所有節點都被處理過后結束
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 ("Cost from the start to each node:")
print (costs)

 

四、小結

  • 廣度有限搜索用於在非加權圖中查找最短路徑。
  • 迪傑斯特拉算法用於在加權圖中查找最短路徑。
  • 僅當權重為正時迪傑斯特拉算法才管用。
  • 如果圖中包含負權邊,考慮使用貝爾曼-福德(Bellman-Ford)算法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM