計算機網路上的 Dijkstra's Algorithm 求最短路徑
計算機網路上的 Dijkstra’s Algorithm 求最短路徑
紀錄 2026/05/20 計算機網路課程。
何謂 Dijkstra’s Algortihm?
Dijkstra’s algorithm 是一種用來解決「單一起點最短路徑」的演算法,也就是從某個起點出發,找出到圖中其他所有節點的最短距離,適用於邊權重非負數的加權圖,例如道路距離、網路傳輸成本、地圖導航等情境。
Dijkstra’s Algorithm 的演算主要思路為每次都選擇目前距離起點最近、且尚未確定最短距離的節點,然後用這個節點去更新它鄰居的距離。
基本概念
Dijkstra’s algorithm 會維護兩個資訊(以寫程式上來說):
| 項目 | 說明 |
|---|---|
dist[] | 從起點到每個節點目前已知的最短距離 |
visited[] | 該節點的最短距離是否已經確定 |
一開始起點距離設為 ,其他節點距離設為無限大 ,之後演算法會不斷挑選目前 dist 最小的未拜訪節點,並更新它相鄰節點的距離,這個更新動作稱為 Relaxation,鬆弛操作。
時間複雜度
若用普通陣列尋找最小距離節點,時間複雜度通常是 , 表示節點或稱頂點 Vertices。
若使用 priority queue,這樣的實作可改善成 , 表示邊數。
一個計算的範例
Given an undirected weight graph following, find the shortest path and cost from point A to point F.

Solution:
d(B) stand for “distance of vertex B”.
P(B) stand for “Predecessor of vertex B”. Predecessor refers to the vertex before vertex B, A.
| Set | |||||
|---|---|---|---|---|---|
| (Visit E) | |||||
| (Visit B) | (Already Visited) | ||||
| (Already Visited) | (Visit D) | (Already Visited) | |||
| (Already Visited) | (Visit C) | (Already Visited) | (Already Visited) | ||
| (Already Visited) | (Already Visited) | (Already Visited) | (Already Visited) | (Visit F) |
From the table above, the shortest path and cost are as follows:
由於 A 作為起點,因此先放進 Set 集合當中,接著就進到第一個 Round。第一個 Round 當中,判斷從 A 走到 B 的距離(尋找所有鄰居節點),是 4,因此 ,且走到 節點的前一個節點為 ,因此 ,以此類推。
由於從 A 走起無法直接走到 C(A 跟 C 不是鄰居),所以 ,先暫時設定無限。
第一回合走完後,尋找當中的最低 cost,發現是 ,因此選他進入集合,目前暫且走到 E 這一個節點。
接著從 E 開始作為第二回合,一樣尋找他的鄰居節點,需注意的是此時 cost 已經累積到 3 了,因為從 A 走到 E 要花 3 cost,之後若走到其他節點,例如 E 走到 C 並不是 ,而是 。
將整個表格都算完以後,最後從 F 的 開始,往 、 的方向開始做回溯,每次回溯都要記錄其 Predecessor 的節點,直到遇到有 的為止。
這題記錄完後會長成 ,但你要反過來寫,因為 A 是起點,所以最後答案是 。
最小 cost 的話直接看 ,當中 就是最小 cost。
練習題
Given an undirected weight graph following, find the shortest path and cost from point A to point F.

| Set | |||||
|---|---|---|---|---|---|
| (Visit D) | |||||
| (Visit B) | (Already Visited) | ||||
| (Already Visited) | (Already Visited) | (Visit E) | |||
| (Already Visited) | (Visit C) | (Already Visited) | (Already Visited) | ||
| (Already Visited) | (Already Visited) | (Already Visited) | (Already Visited) | (Visit F) |
From the table above, the shortest path and cost are as follows:

