Dijikstra
๐โโ๏ธ ๋ค์ด๊ฐ๋ฉฐ
์ด๋ฒ ์๊ฐ์๋ dijikstra๋ฅผ ๋ฐฐ์๋ณด์
์ฐ์ ์ด๋ฅผ ์ดํดํ๊ธฐ ์ํด์๋ Priority Queue์ ์ ํํ์ต์ด ๋์ด์์ด์ผํ ๊ฒ์ด๋ค.
๋ชจ๋ฅธ๋ค๋ฉด ์ด์ ์ Pritority Queue ๊ด๋ จ ๊ธ์ ๋ณด๊ณ ์ค์
dijikstra๋ ์ต์๋น์ฉ์ ๊ตฌํ ๋ ๋ง์ด ์ฐ์ธ๋ค.
์ ๊ทธ๋ฆผ์ ํ ๋๋ก ์๋์ ๊ตฌํํด๋ณด์
โ ์ฝ๋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
// dijikstra
import java.util.PriorityQueue;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = 5;
// 1. graph ์์ฑ
List<int[]>[] graph = new ArrayList[N+1];
for (int i = 1; i < N+1; i++) {
graph[i] = new ArrayList<>();
}
// 2. ๊ฐ ๋์
graph[1].add(new int[] {2, 2});
graph[1].add(new int[] {3, 5});
graph[2].add(new int[] {4, 2});
graph[2].add(new int[] {3, 1});
graph[3].add(new int[] {5, 3});
// 3. dist ๋ฐฐ์ด ์ด๊ธฐํ
int[] dist = new int[N+1];
for (int i = 1; i < N+1; i++) {
dist[i] = Integer.MAX_VALUE;
}
// 4. ์์์ ์ ๋น์ฉ์ 0
dist[1] = 0;
// 5. pq -> ๋น์ฉ asc
PriorityQueue<int[]> pq = new PriorityQueue<> (
(a,b) -> a[1] - b[1]
);
// 6. ์ด๊ธฐ๊ฐ ์ฝ์
pq.offer(new int[] {1, 0});
// 7. ํ์
while (!pq.isEmpty()) {
int[] cur_pos = pq.poll();
int cur_node =cur_pos[0];
int cur_cost = cur_pos[1];
// 7-1. ํ์ฌ ๋น์ฉ์ด dist๋ณด๋ค ํฌ๋ฉด skip
if (cur_cost > dist[cur_node]) continue;
// 7-2. ์๋ค๋ฉด
for (int[] next : graph[cur_node]) {
int next_node = next[0];
int next_cost = cur_cost + next[1];
if (dist[next_node] > next_cost) {
dist[next_node] = next_cost;
pq.offer(new int[] {next_node, next_cost});
}
}
}
// 8. ์ถ๋ ฅ
for (int i = 1; i < N+1; i++) {
System.out.println(dist[i]);
}
}
}
This post is licensed under CC BY 4.0 by the author.

