【算法圖解】——狄克斯特拉算法

狄克斯特拉算法

  • 加權圖——提高/降低某些邊的權重
  • 加權圖:“邊”上有了權重(例如:時間)
  • 狄克斯特拉算法:找到總權重最小的路徑

計算非加權圖的最短路徑——廣度優先算法
計算加權圖的最小權重——狄克斯特拉算法

**注意:**當圖中存在負權重時,無法使用狄克斯特拉算法

實現算法

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

節點

"""狄克斯特拉算法"""
# ------------整個圖的散列表(字典)--------
graph = {}

# 起點
graph["start"] = {} # 起點是一個散列表(字典)
graph["start"]["A"] = 6 # 存儲權重,start-A
graph["start"]["B"] = 2 # 存儲權重,start-B
print(graph["start"].keys())

# 其他節點
graph["A"] = {} # A節點也是一個字典
graph["A"]["destination"] = 1 # A-終點

graph["B"] = {}
graph["B"]["A"] = 3 # B-A
graph["B"]["destination"] = 5 # B - 終點

# 終點
graph["destination"] = {} # 終點沒有任何鄰居
print(graph["B"])

利用字典的——實現節點
利用字典的鍵值——實現權重

實時計算消耗的權重

# ---------實時計算消耗權重的散列表(字典)------------
infinity = float("inf") # python中表示無窮大,因爲此刻的開銷還不知搭配

costs = {}
costs["A"] = 6
costs["B"] = 2
# costs["destination"] = infinity # 表示路徑還沒選擇,此時到達終點所消耗權重未知

存儲父節點

# -----------存儲父節點的散列表----------------
parents = {}
parents["A"] = "start"
parents["B"] = "start"
parents["destination"] = 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 node:
    cost = costs[node]
    neighbors = graph[node]
    for i in neighbors.keys(): # 遍歷當前節點的所有鄰居
        new_cost = cost + neighbors[i] # neighbors[i]相當於neighbors.value鍵值,即對應的權重值
        if costs[i] > new_cost:  # 原先直接前往i節點的開銷和現在路勁進行比較
            costs[i] = new_cost
            parents[i] = node
    processed.append(node)
    node = find_lowest_cost_node(costs)
    
print(costs["destination"])

6

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章