다익스트라 알고리즘은 그래프에서 하나의 정점에서 다른 모든 정점까지의 최단 경로를 구하는 알고리즘입니다. 네덜란드의 컴퓨터 과학자 **에츠허르 다익스트라(Edsger W. Dijkstra)**가 개발했어요.
"GPS가 길 찾을 때 최단 경로를 계산하는 기본 원리!"
바로 다익스트라 알고리즘입니다.
배열 사용 | O(V²) |
우선순위 큐(힙) | O(E log V) |
import java.util.*;
public class DijkstraExample {
static class Node implements Comparable<Node> {
int index, distance;
public Node(int index, int distance) {
this.index = index;
this.distance = distance;
}
// 거리 기준으로 오름차순 정렬
@Override
public int compareTo(Node other) {
return Integer.compare(this.distance, other.distance);
}
}
static final int INF = (int)1e9;
static ArrayList<ArrayList<Node>> graph = new ArrayList<>();
static int[] dist;
public static void dijkstra(int start) {
PriorityQueue<Node> pq = new PriorityQueue<>();
dist[start] = 0;
pq.offer(new Node(start, 0));
while (!pq.isEmpty()) {
Node now = pq.poll();
int nowIdx = now.index;
int nowDist = now.distance;
if (dist[nowIdx] < nowDist) continue;
for (Node next : graph.get(nowIdx)) {
int cost = dist[nowIdx] + next.distance;
if (cost < dist[next.index]) {
dist[next.index] = cost;
pq.offer(new Node(next.index, cost));
}
}
}
}
public static void main(String[] args) {
int n = 6; // 노드 수
int start = 1;
dist = new int[n + 1];
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
dist[i] = INF;
}
// 예시 간선 추가
graph.get(1).add(new Node(2, 2));
graph.get(1).add(new Node(3, 5));
graph.get(2).add(new Node(3, 3));
graph.get(2).add(new Node(4, 4));
graph.get(3).add(new Node(4, 2));
graph.get(4).add(new Node(5, 1));
graph.get(5).add(new Node(6, 2));
dijkstra(start);
// 결과 출력
for (int i = 1; i <= n; i++) {
if (dist[i] == INF) {
System.out.println(i + "번 노드: 도달 불가");
} else {
System.out.println(i + "번 노드까지의 최단 거리: " + dist[i]);
}
}
}
}
1번 노드까지의 최단 거리: 0
2번 노드까지의 최단 거리: 2
3번 노드까지의 최단 거리: 5
4번 노드까지의 최단 거리: 7
5번 노드까지의 최단 거리: 8
6번 노드까지의 최단 거리: 10
알고리즘 이름 | 다익스트라 알고리즘 |
목적 | 하나의 정점에서 모든 정점까지 최단 거리 계산 |
조건 | 음의 가중치 불가, 연결된 그래프 |
성능 | 힙 사용 시 O(E log V) |
사용 예 | GPS, 네트워크 경로, 최단시간 계산 등 |
이진 탐색(Binary Search) (0) | 2025.06.15 |
---|---|
선형 탐색(Linear Search) (1) | 2025.06.15 |
병합 정렬(Merge Sort) (0) | 2025.06.15 |
퀵 정렬(Quick Sort) (0) | 2025.06.15 |
버블 정렬(Bubble Sort) (0) | 2025.06.15 |