본문 바로가기

ProgramSoliving

프로그래머스 : 섬 연결하기

반응형
import java.util.*;

class Solution {
    
    static int[] parrent;
    
    public int Find(int x){
        
        if(x==parrent[x]){
            return x;
        }
        
        return parrent[x] = Find(parrent[x]);
    }
    
    public boolean Union(int x, int y){
        x = Find(x);
        y = Find(y);
        
        if(x==y)
            return false;
        parrent[x] = y;
        return true;
    }
    
    public class NC implements Comparator<int[]>{
        @Override
        public int compare(int[] o1,int[] o2) {
            return o1[2] - o2[2];
        }
    }
    
    public int solution(int n, int[][] costs) {
        int answer = 0;
        parrent = new int[n+1];
        Arrays.sort(costs,new NC());
        for(int i=1;i<=n;i++)
            parrent[i] = i;
        int i=0;
        while(n!=1){
            int x = costs[i][0];
            int y = costs[i][1];
            int w = costs[i][2];
            if(Union(x,y)){
                answer+=w;
                n--;
            }
            i++;
        }
        return answer;
    }
}
반응형