天天看點

學習筆記 | Dijkstra單源最短路

Dijkstra算法

學習筆記 | Dijkstra單源最短路
學習筆記 | Dijkstra單源最短路

代碼實作

# 迪克斯特拉算法: 計算權重圖中的最短路徑
# graph: 起點start,a,b,終點fin之間的距離

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"] = {}

# costs: 起點到 a,b,fin的開銷
infinity = float("inf")
costs = {}
costs["a"] = 6
costs["b"] = 2
costs["fin"] = infinity

# parents: 存儲父節點,記錄最短路徑
parents = {}
parents["a"] = "start"
parents["b"] = "start"
parents["fin"] = None

# processed: 記錄處理過的節點,避免重複處理
processed = []

# find_lowest_cost_node(costs): 傳回開銷最低的點
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

# Dijkstra implement
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)

tmp = "fin"
path = ["fin"]
while parents[tmp] != "start":
    path.append(parents[tmp])
    tmp = parents[tmp]
    
path.append("start")
for i in range(0,len(path)):
    print(path[len(path)-i-1])
           

輸出:

學習筆記 | Dijkstra單源最短路

步驟

Dijkstra算法包含4個步驟:

(1) 找出最便宜的節點,即可在最短時間内前往的節點。

(2) 對于該節點的鄰居,檢查是否有前往它們的更短路徑,如果有,就更新其開銷。 (3) 重複這個過程,直到對圖中的每個節點都這樣做了。

(4) 計算最終路徑。

注意

  • 不能将Dijkstra算法用于包含負權邊的圖。