1
+ import java .util .ArrayList ;
2
+ import java .util .PriorityQueue ;
3
+ class Solution {
4
+
5
+ // 간선의 정보를 저장할 오브젝트
6
+ class Edge {
7
+ int to , weight ;
8
+
9
+ Edge (int to , int weight ) {
10
+ this .to = to ;
11
+ this .weight = weight ;
12
+ }
13
+ }
14
+
15
+ public int solution (int n , int [][] costs ) {
16
+ int answer = 0 ;
17
+ ArrayList <ArrayList <Edge >> edges = new ArrayList <>();
18
+ for (int i = 0 ; i < n ; i ++)
19
+ edges .add (new ArrayList <>());
20
+ // 주어진 간선의 정보를 가공하여 저장
21
+ for (int [] cost : costs ) {
22
+ edges .get (cost [0 ]).add (new Edge (cost [1 ], cost [2 ]));
23
+ edges .get (cost [1 ]).add (new Edge (cost [0 ], cost [2 ]));
24
+ }
25
+ // MST - Prim Algorithm
26
+ // 간선 비용을 기준으로 오름차순
27
+ PriorityQueue <Edge > pq = new PriorityQueue <>((o1 , o2 ) -> o1 .weight - o2 .weight );
28
+ boolean [] visited = new boolean [n ];
29
+ pq .offer (new Edge (0 , 0 ));
30
+ int cnt = 0 ; // MST를 구성하는 간선은 n-1개면 충분
31
+ while (!pq .isEmpty () && cnt < n ) {
32
+ Edge cur = pq .poll ();
33
+ if (visited [cur .to ])
34
+ continue ;
35
+ visited [cur .to ] = true ;
36
+ cnt ++;
37
+ answer += cur .weight ;
38
+ // 방문하지 않은 노드로가는 간선 추가
39
+ for (Edge edge : edges .get (cur .to )) {
40
+ if (!visited [edge .to ])
41
+ pq .offer (edge );
42
+ }
43
+ }
44
+ return answer ;
45
+ }
46
+ }
0 commit comments