Post

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.

Trending Tags