ダイクストラ最短経路法
優先度付きキューと緩和表を用いた最短経路探索のステップ実行。
| ノード | 距離 | 直前 | 確定 |
|---|---|---|---|
| A | — | ||
| B | — | ||
| C | — | ||
| D | — | ||
| E | — | ||
| F | — |
このツールについて
ダイクストラ法は、辺の重みが負でないグラフで、1 つの始点から他のすべてのノードへの最短経路を求めます。優先度付きキューから既知の距離が最小の未確定ノードを取り出してその距離を確定させ、そこから出る辺を緩和する、という操作を繰り返します。そのノードを経由したほうが隣接ノードへの距離が短くなるなら、隣接ノードの距離と直前のノードを更新します。
このラボは重み付きグラフ上で、取り出しと緩和のすべてをアニメーションで示し、距離表と優先度付きキューを常に表示し、選んだ始点と終点の間の最短経路を最後にハイライトします。
使い方 ダイクストラ最短経路法
- 始点と終点のノードを選びます。
- 再生します。各ステップでは、キューから最も近いノードを取り出すか、辺を 1 本緩和します。ステータス行に 4 + 3 = 7 < 9 のような計算が表示されます。
- 距離表を追います。「確定」はもう変わらない距離の印で、「prev」は各最良経路がどこから来たかを記録します。
- 終点が取り出されると、prev 列をたどって最短経路を復元し、グラフ上に描きます。
使用例
距離が改善される緩和
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 のまま
5 つの言語による実装
同じアルゴリズムを 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(英語)です。
なぜ正しいのか、そして正しくない場合
ノードが取り出された時点で、他の未確定ノードはどれも同じかそれ以上遠く、重みが負でないので、後から見つかる経路のほうが短くなることはありません。負の辺が 1 本でもあるとこの論証は成り立ちません。負の重みを含むグラフにはベルマン–フォード法を使います。
計算量
- 二分ヒープを使う場合:O((V + E) log V)。
- ヒープを使わず配列だけの場合:O(V²)。非常に密なグラフではこちらも十分速い。
- 1 組の始点・終点だけが必要なら、終点を取り出した時点で止めれば処理を減らせます。A* はさらに終点までの推定距離を加えます。
よくある質問
ツールの仕様やセキュリティに関する疑問にお答えします。
同じノードがキューに複数回現れるのはなぜですか?
この「遅延」版では、距離が改善されるたびにその場で更新する代わりに新しいエントリを追加します。古いエントリは、取り出したときにノードがすでに確定していれば読み飛ばされます。
結果は木になりますか?
はい。prev ポインタは始点を根とする最短経路木になり、到達可能なすべてのノードへの最良の経路を一度に表します。
ダイクストラ法はどこで使われていますか?
OSPF や IS-IS などのルーティングプロトコル、地図のナビゲーション(通常は A* と前処理を組み合わせる)、ネットワーク遅延の設計、多くのゲーム AI の経路探索です。
入力したデータやファイルは安全ですか?
完全に安全です。本ツールは100%ブラウザ内部で動作し、データがサーバーに送信されることは一切ありません。
関連ツール
注目のプロダクト tech-fun.net
便利なAI・生産性ツールとゲーム
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.