본문 바로가기

알고리즘/프로그래머스

[프로그래머스] 네트워크 / JAVA

문제링크 : https://programmers.co.kr/learn/courses/30/lessons/43162

 

코딩테스트 연습 - 네트워크

네트워크란 컴퓨터 상호 간에 정보를 교환할 수 있도록 연결된 형태를 의미합니다. 예를 들어, 컴퓨터 A와 컴퓨터 B가 직접적으로 연결되어있고, 컴퓨터 B와 컴퓨터 C가 직접적으로 연결되어 있

programmers.co.kr

import java.util.*;
class Solution {
    public static int par[];
    public static int find(int x){
        if(par[x] == x) return x;
        return par[x] = find(par[x]);
    }
    public static void union(int x, int y){
        int a = find(x);
        int b = find(y);
        if(a!=b){
            par[a] = b;
        }
    }
    public static int solution(int n, int[][] computers) {
        int answer = 0;
        ArrayList<Integer> adj[] = new ArrayList[n];
        par = new int[n];

        for(int i=0;i<n;i++){
            adj[i] = new ArrayList<Integer>();
            par[i] = i;
        }
        for(int i=0;i<computers.length;i++){
            for(int j=i+1;j<computers[i].length;j++){
                if(computers[i][j] == 1){
                    union(i,j);
                }
            }
        }
        boolean isCounted[] = new boolean[n];
        for(int i=0;i<n;i++){
            int parent = find(i);
            if(isCounted[parent]) continue;
            isCounted[parent] = true;
            answer++;
        }
        return answer;
    }
}