https://school.programmers.co.kr/learn/courses/30/lessons/42861
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
[문제 풀이]
크루스칼 알고리즘을 이용하여 문제를 풀었습니다.
섬 연결하기 문제는 전형적인 최소신장트리 문제입니다. 최소신장트리의 종류는 몇 가지가 존재하는데 그 중 하나가 크루스칼 알고리즘입니다. 알고리즘에 대한 내용은 아래 링크를 참고 바랍니다.
https://steady-life.tistory.com/128
서로소 집합(Disjoint Set, Union-Find)
서로소 집합 교집합이 공집합인 집합(서로소 집합)들의 정보를 확인(Find)하고 조작(Union)할 수 있는 자료구조 2가지 연산으로 이루어져 있습니다 Union 연산 - 어떤 두 원소 a, b 에 대해서 union(a, b)
steady-life.tistory.com
https://steady-life.tistory.com/124
[JAVA]
import java.util.Arrays;
import java.util.Comparator;
class Solution {
static int[] island;
public static int unionFind(int i){
if(island[i] == i)
return i;
else
return unionFind(island[i]);
}
public static int solution(int n, int[][] costs) {
int answer = 0;
island = new int[n];
Arrays.sort(costs, new Comparator<int[]>(){
public int compare(int[] o1, int[] o2){
return o1[2] - o2[2];
}
});
for(int i = 0; i < n; i ++)
island[i] = i;
for(int[] item : costs){
int a = unionFind(item[0]);
int b = unionFind(item[1]);
if(a != b){
answer += item[2];
island[a] = b;
}
}
return answer;
}
}
'algorithm > 프로그래머스' 카테고리의 다른 글
프로그래머스_도둑질(JAVA) (0) | 2023.02.28 |
---|---|
프로그래머스_단속카메라(JAVA) (0) | 2022.11.21 |
프로그래머스_구명보트(JAVA) (0) | 2022.11.21 |
프로그래머스_큰 수 만들기(JAVA) (0) | 2022.11.21 |
프로그래머스_조이스틱(JAVA) (0) | 2022.11.21 |