Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 93db6f8

Browse files
committed
백제완: [PG] 42861 섬 연결하기_241018
1 parent 6621b13 commit 93db6f8

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎Programmers/Level3/JW_42861.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /