Dijkstra 最短路徑演算法
加權圖最短路徑單步探索,即時展示鬆弛表與優先佇列計算。
| 節點 | 距離 | 前驅 | 已確定 |
|---|---|---|---|
| A | — | ||
| B | — | ||
| C | — | ||
| D | — | ||
| E | — | ||
| F | — |
關於本工具
Dijkstra 演算法在邊權非負的圖中,求出從一個源點到所有其他節點的最短路徑。它不斷從優先佇列中取出當前已知距離最小、尚未確定的節點,把它的距離標記為最終值,並“鬆弛”它的出邊:如果經由它到達某個鄰居更近,就更新該鄰居的距離和前驅。
本實驗室在帶權圖上演示每一次出隊和每一次鬆弛,始終顯示距離表和優先佇列,並高亮你所選起點與終點之間的最短路徑。
使用方法 Dijkstra 最短路徑演算法
- 選擇起點和終點。
- 點選播放。每一步要麼從佇列中取出最近的節點,要麼鬆弛一條邊;狀態列會給出算式,例如 4 + 3 = 7 < 9。
- 跟隨距離表:“已確定”表示距離不會再變,“前驅”記錄每條最佳路徑從哪裡來。
- 當終點被取出時,沿前驅列回溯出最短路徑,並在圖上畫出。
範例
一次成功的鬆弛
dist[B] = 4,邊 B→C 權重 3,dist[C] = 9
4 + 3 = 7 < 9 → dist[C] = 7,prev[C] = B
一次無效的鬆弛
dist[D] = 5,邊 D→C 權重 4,dist[C] = 7
5 + 4 = 9 不更短 → 保持 7
五種語言的程式碼實作
同一演算法的 Python、JavaScript、Java、Go 和 C++ 實作。每段程式都完整可執行,註解中標出了它的輸出結果。
import heapq
graph = {
"A": [("B", 4), ("C", 2)],
"B": [("D", 5)],
"C": [("B", 1), ("D", 8)],
"D": [("E", 3)],
"E": [],
}
def dijkstra(source):
dist = {node: float("inf") for node in graph}
prev = {}
dist[source] = 0
pq = [(0, source)]
while pq:
d, node = heapq.heappop(pq)
if d > dist[node]:
continue # stale queue entry
for nxt, w in graph[node]:
if d + w < dist[nxt]: # relax the edge
dist[nxt] = d + w
prev[nxt] = node
heapq.heappush(pq, (dist[nxt], nxt))
return dist, prev
def path(prev, target):
out = [target]
while out[-1] in prev:
out.append(prev[out[-1]])
return out[::-1]
dist, prev = dijkstra("A")
print(dist) # {'A': 0, 'B': 3, 'C': 2, 'D': 8, 'E': 11}
print(path(prev, "E")) # ['A', 'C', 'B', 'D', 'E'] const graph = {
A: [['B', 4], ['C', 2]],
B: [['D', 5]],
C: [['B', 1], ['D', 8]],
D: [['E', 3]],
E: [],
};
// Minimal binary heap of [distance, node] pairs.
class MinHeap {
constructor() { this.a = []; }
get size() { return this.a.length; }
push(item) {
const a = this.a;
a.push(item);
for (let i = a.length - 1; i > 0;) {
const p = (i - 1) >> 1;
if (a[p][0] <= a[i][0]) break;
[a[p], a[i]] = [a[i], a[p]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
for (let i = 0; ;) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && a[l][0] < a[m][0]) m = l;
if (r < a.length && a[r][0] < a[m][0]) m = r;
if (m === i) break;
[a[m], a[i]] = [a[i], a[m]];
i = m;
}
}
return top;
}
}
function dijkstra(source) {
const dist = Object.fromEntries(Object.keys(graph).map((n) => [n, Infinity]));
const prev = {};
dist[source] = 0;
const pq = new MinHeap();
pq.push([0, source]);
while (pq.size > 0) {
const [d, node] = pq.pop();
if (d > dist[node]) continue; // stale queue entry
for (const [next, w] of graph[node]) {
if (d + w < dist[next]) { // relax the edge
dist[next] = d + w;
prev[next] = node;
pq.push([dist[next], next]);
}
}
}
return { dist, prev };
}
function path(prev, target) {
const out = [target];
while (prev[out[0]] !== undefined) out.unshift(prev[out[0]]);
return out;
}
const { dist, prev } = dijkstra('A');
console.log(dist); // { A: 0, B: 3, C: 2, D: 8, E: 11 }
console.log(path(prev, 'E').join(' → ')); // A → C → B → D → E import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;
public class Main {
record Edge(String to, int weight) {}
record Entry(int dist, String node) {}
static final Map<String, List<Edge>> GRAPH = Map.of(
"A", List.of(new Edge("B", 4), new Edge("C", 2)),
"B", List.of(new Edge("D", 5)),
"C", List.of(new Edge("B", 1), new Edge("D", 8)),
"D", List.of(new Edge("E", 3)),
"E", List.of()
);
public static void main(String[] args) {
Map<String, Integer> dist = new TreeMap<>();
Map<String, String> prev = new HashMap<>();
for (String n : GRAPH.keySet()) dist.put(n, Integer.MAX_VALUE);
dist.put("A", 0);
PriorityQueue<Entry> pq = new PriorityQueue<>((x, y) -> Integer.compare(x.dist(), y.dist()));
pq.add(new Entry(0, "A"));
while (!pq.isEmpty()) {
Entry e = pq.poll();
if (e.dist() > dist.get(e.node())) continue; // stale queue entry
for (Edge edge : GRAPH.get(e.node())) {
int nd = e.dist() + edge.weight();
if (nd < dist.get(edge.to())) { // relax the edge
dist.put(edge.to(), nd);
prev.put(edge.to(), e.node());
pq.add(new Entry(nd, edge.to()));
}
}
}
System.out.println(dist); // {A=0, B=3, C=2, D=8, E=11}
LinkedList<String> path = new LinkedList<>(List.of("E"));
while (prev.containsKey(path.getFirst())) path.addFirst(prev.get(path.getFirst()));
System.out.println(path); // [A, C, B, D, E]
}
} package main
import (
"container/heap"
"fmt"
"math"
)
type Edge struct {
To string
Weight int
}
var graph = map[string][]Edge{
"A": {{"B", 4}, {"C", 2}},
"B": {{"D", 5}},
"C": {{"B", 1}, {"D", 8}},
"D": {{"E", 3}},
"E": {},
}
// Item and PQ implement container/heap's interface.
type Item struct {
Dist int
Node string
}
type PQ []Item
func (q PQ) Len() int { return len(q) }
func (q PQ) Less(i, j int) bool { return q[i].Dist < q[j].Dist }
func (q PQ) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *PQ) Push(x any) { *q = append(*q, x.(Item)) }
func (q *PQ) Pop() any {
old := *q
it := old[len(old)-1]
*q = old[:len(old)-1]
return it
}
func dijkstra(source string) (map[string]int, map[string]string) {
dist := map[string]int{}
prev := map[string]string{}
for n := range graph {
dist[n] = math.MaxInt
}
dist[source] = 0
pq := &PQ{{0, source}}
for pq.Len() > 0 {
it := heap.Pop(pq).(Item)
if it.Dist > dist[it.Node] {
continue // stale queue entry
}
for _, e := range graph[it.Node] {
if nd := it.Dist + e.Weight; nd < dist[e.To] { // relax the edge
dist[e.To] = nd
prev[e.To] = it.Node
heap.Push(pq, Item{nd, e.To})
}
}
}
return dist, prev
}
func main() {
dist, prev := dijkstra("A")
fmt.Println(dist) // map[A:0 B:3 C:2 D:8 E:11]
path := []string{"E"}
for p, ok := prev[path[0]]; ok; p, ok = prev[path[0]] {
path = append([]string{p}, path...)
}
fmt.Println(path) // [A C B D E]
} #include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include <vector>
using Graph = std::map<std::string, std::vector<std::pair<std::string, int>>>;
const Graph graph = {
{"A", {{"B", 4}, {"C", 2}}},
{"B", {{"D", 5}}},
{"C", {{"B", 1}, {"D", 8}}},
{"D", {{"E", 3}}},
{"E", {}},
};
int main() {
std::map<std::string, int> dist;
std::map<std::string, std::string> prev;
for (const auto& [node, edges] : graph) dist[node] = INT_MAX;
dist["A"] = 0;
using Item = std::pair<int, std::string>; // (distance, node)
std::priority_queue<Item, std::vector<Item>, std::greater<Item>> pq;
pq.push({0, "A"});
while (!pq.empty()) {
auto [d, node] = pq.top();
pq.pop();
if (d > dist[node]) continue; // stale queue entry
for (const auto& [next, w] : graph.at(node)) {
if (d + w < dist[next]) { // relax the edge
dist[next] = d + w;
prev[next] = node;
pq.push({dist[next], next});
}
}
}
for (const auto& [node, d] : dist) std::cout << node << '=' << d << ' ';
std::cout << '\n'; // A=0 B=3 C=2 D=8 E=11
std::vector<std::string> path = {"E"};
while (prev.count(path.back())) path.push_back(prev[path.back()]);
std::reverse(path.begin(), path.end());
for (const auto& n : path) std::cout << n << ' ';
std::cout << '\n'; // A C B D E
} LeetCode 練習題
用到這一演算法的經典題目,適合在玩過本實驗室後動手練習。連結將開啟 LeetCode。
為什麼正確,何時失效
一個節點被取出時,其他未確定的節點都至少和它一樣遠;又因為邊權非負,之後不可能出現更短的路徑。只要有一條負權邊,這個論證就不成立;含負權的圖請使用 Bellman–Ford 演算法。
複雜度
- 使用二叉堆:O((V + E) log V)。
- 不用堆、只用普通陣列:O(V²),在非常稠密的圖上反而有競爭力。
- 只求單對最短路時,終點出隊即可停止;A* 演算法更進一步,加入到終點的距離估計。
常見問題
解答您關心的工具使用與資料安全相關問題。
為什麼同一個節點會多次出現在佇列中?
這是“惰性”實現:距離變小時直接壓入新條目,而不是原地修改。舊條目出隊時因節點已確定而被跳過。
結果是一棵樹嗎?
是的。前驅指標構成以源點為根的最短路徑樹,一次給出到所有可達節點的最佳路徑。
Dijkstra 用在哪裡?
OSPF、IS-IS 等路由協議,地圖導航(通常配合 A* 和預處理),網路延遲規劃,以及許多遊戲 AI 的尋路系統。
使用該工具時我的資料安全嗎?
絕對安全。本工具採用 100% 純客戶端本地計算技術,所有資料與檔案均在您的本機瀏覽器記憶體中處理,絕不上傳到任何伺服器。
相關推薦工具
精選產品 tech-fun.net
探索更多獨立的實用 AI 與生產力工具
Nihongo GameBox
从五十音图基础到 JLPT N1 词汇与四字熟语,通过复古街机打字小游戏轻松锻炼假名盲打与反应力。
ResumeGPT
通过多智能体 LLM 流水线、定时职位搜寻和可复用模板,为每一个求职机会量身定制简历与求职信。
CollectMind
借助 Chrome 内置 Gemini Nano 端侧大模型,将书签变为可搜索、可总结、可对话的个人知识库,零云端上传。