prim
๐โโ๏ธ ๋ค์ด๊ฐ๋ฉฐ
์ด๋ฒ์๋ prim์ ๋ํด ์์๋ณด์
๊ฐ์ค์น (๋น์ฉ, ๊ฑฐ๋ฆฌ)๊ฐ ๋์จ๋ค๊ณ ํญ์ ํท๊ฐ๋ฆฌ์ง๋ง์
dijikstra -> ํน์ ๋ ธ๋๊น์ง ๋๋ฌํ ๋์ ์ต์๊ฑฐ๋ฆฌ
prim -> ์ ์ฒด๋ฅผ ์ต์ ๋น์ฉ์ผ๋ก ์ฐ๊ฒฐ (์๋ฐฉํฅ ํ์)
ํน์ง
prim์ ์ค๋ฆ์ฐจ์์ ํ๊ธฐ ๋๋ฌธ์ visited[]๋ง ํ์ฉํ๋ฉด ๋๊ฒ ๋ค dijikstra์ฒ๋ผ ๊ฐ ๋น๊ต๊ฐ ํ์ ์๊ฒ ๋ค.
why? ->
์ด์ฐจํผ ์ ๋ ฌ์ ํตํด ์์๊ฐ๋ถํฐ ๋์ดํ๋๊น
๊ฑฐ๋์ ๋ฏธํ๊ณ ๋ฌธ์ ๋ก ๋ฐฐ์๋ณด์ (์๋ ๋งํฌ ํด๋ฆญ)
์ฌ ์ฐ๊ฒฐํ๊ธฐ
โ ์ฝ๋
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
// prim
import java.util.PriorityQueue;
import java.util.List;
import java.util.ArrayList;
class Solution {
public int solution(int n, int[][] costs) {
int answer = 0;
// 1. graph
List<int[]>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
// 2. ์ ์ฒด๋ฅผ ์ต์๋น์ฉ์ผ๋ก ์ํ (prim) -> ์๋ฐฉํฅ
for (int[] c : costs) {
int cur_node = c[0];
int cur_to = c[1];
int cur_cost = c[2];
graph[cur_node].add(new int[] {cur_to, cur_cost});
graph[cur_to].add(new int[] {cur_node, cur_cost});
}
// 3. visited[]
boolean[] visited = new boolean[n];
// 4. pq -> ๋น์ฉ ์ค๋ฆ์ฐจ์ (์์ ๊ฐ๋ถํฐ ๋์ด)
PriorityQueue<int[]> pq = new PriorityQueue<> (
(a,b) -> a[1] - b[1]
);
// 5. ์์์ ์ฝ์
(start_node, start_cost);
pq.offer(new int[] {0, 0});
// 6. prim
while (!pq.isEmpty()) {
int[] cur = pq.poll();
int cur_node = cur[0];
int cur_cost = cur[1];
// 6-1. ๋ง์ฝ ๋ฐฉ๋ฌธํ๋ค๋ฉด skip
if (visited[cur_node]) continue;
// 6-2. ๋ฐฉ๋ฌธ ์ํ๋ค๋ฉด -> ๋ฐฉ๋ฌธ
visited[cur_node] = true;
// 6-3. ๊ฐ ์ถ๊ฐ (์ด์ฐจํผ ์ค๋ฆ์ฐจ์์ด๋ผ ์ ์ผ ์์๊ฒ๋ถํฐ ์์๋๋ก ๋์ด)
answer += cur_cost;
// 6-4. next_node
for (int[] next : graph[cur_node]) {
int next_node = next[0];
int next_cost = next[1];
// 6-5. ๋ง์ฝ next_node ๋ฐฉ๋ฌธ ์ํ๋ค๋ฉด
if (!visited[next_node]) {
pq.offer(new int[] {next_node, next_cost});
}
}
}
return answer;
}
}
This post is licensed under CC BY 4.0 by the author.
