인터랙티브 랩브라우저에서 실행

다익스트라 최단 경로

우선순위 큐와 이완 테이블을 통한 단계별 최단 경로 탐색.

속도:
4215810263ABCDEF
거리 표
노드거리이전확정
A—
B—
C—
D—
E—
F—
우선순위 큐(작은 것부터)
비어 있음
의사코드
1dist[s] = 0; pq = [(0, s)]
2while pq not empty:
3 (d, u) = pq.popMin()
4 if u == target: done
5 for each edge (u, v, w):
6 if d + w < dist[v]:
7 dist[v] = d + w; prev[v] = u
8 pq.push((dist[v], v))

이 도구에 대하여

다익스트라 알고리즘은 간선 가중치가 음수가 아닌 그래프에서 하나의 출발점에서 다른 모든 노드까지의 최단 경로를 찾습니다. 우선순위 큐에서 알려진 거리가 가장 짧은 미확정 노드를 꺼내 그 거리를 확정하고, 그 노드에서 나가는 간선을 완화하는 일을 반복합니다. 그 노드를 거치는 쪽이 이웃까지 더 짧다면 이웃의 거리와 이전 노드를 갱신합니다.

이 실험실은 가중 그래프에서 모든 꺼내기와 완화를 애니메이션으로 보여 주고, 거리 표와 우선순위 큐를 항상 표시하며, 선택한 출발점과 도착점 사이의 최단 경로를 마지막에 강조합니다.

사용 방법 다익스트라 최단 경로

  1. 출발 노드와 도착 노드를 고릅니다.
  2. 재생을 누릅니다. 각 단계는 큐에서 가장 가까운 노드를 꺼내거나 간선 하나를 완화합니다. 상태 표시줄에 4 + 3 = 7 < 9 같은 계산이 표시됩니다.
  3. 거리 표를 따라가세요. "확정"은 더 이상 바뀌지 않는 거리이고, "prev"는 각 최선의 경로가 어디서 왔는지 기록합니다.
  4. 도착점이 꺼내지면 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(영어)로 연결됩니다.

왜 올바른가, 그리고 언제 틀리는가

노드를 꺼낸 시점에 다른 미확정 노드는 모두 같거나 더 멀고, 가중치가 음수가 아니므로 나중에 찾은 경로가 더 짧을 수 없습니다. 음수 간선이 하나만 있어도 이 논증은 무너집니다. 음수 가중치가 있는 그래프에는 벨만-포드 알고리즘을 쓰세요.

복잡도

  • 이진 힙 사용 시: O((V + E) log V).
  • 힙 없이 배열만 쓰면: O(V²). 아주 조밀한 그래프에서는 충분히 경쟁력이 있습니다.
  • 출발점-도착점 한 쌍만 필요하면 도착점을 꺼내는 즉시 멈춰 작업을 줄일 수 있습니다. A*는 여기에 도착점까지의 거리 추정치를 더합니다.

자주 묻는 질문

도구 이용과 데이터 보안에 관한 궁금증을 확인하세요.

같은 노드가 큐에 여러 번 나타나는 이유는?

이 "지연" 방식은 거리가 개선될 때마다 제자리에서 갱신하는 대신 새 항목을 넣습니다. 오래된 항목은 꺼낼 때 노드가 이미 확정되어 있으면 건너뜁니다.

결과는 트리인가요?

네. prev 포인터는 출발점을 루트로 하는 최단 경로 트리를 이루며, 도달 가능한 모든 노드까지의 최선 경로를 한 번에 나타냅니다.

다익스트라는 어디에 쓰이나요?

OSPF나 IS-IS 같은 라우팅 프로토콜, 지도 내비게이션(보통 A*와 전처리를 함께 사용), 네트워크 지연 설계, 많은 게임 AI의 경로 탐색입니다.

내 데이터는 안전하게 보호되나요?

네, 완벽하게 안전합니다. 100% 브라우저 메모리 상에서만 동작하며 외부 서버로 일절 전송되지 않습니다.