Union-Find
https://school.programmers.co.kr/learn/courses/30/lessons/43162#
import java.util.*;
class Solution {
static int[] parent;
public int solution(int n, int[][] computers) {
parent = new int[n];
for(int i=0; i<n; i++) {
parent[i] = i;
}
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(computers[i][j] == 1) {
union(i, j);
}
}
}
Set<Integer> set = new HashSet<>();
for(int i=0; i<n; i++) {
set.add(find(i));
}
return set.size();
}
public void union(int x, int y) {
int px = find(x);
int py = find(y);
parent[py] = px;
}
public int find(int x) {
if(parent[x] == x) {
return x;
}
return parent[x] = find(parent[x]);
}
}
for(int i=0; i<n; i++) {
for(int j=i+1; j<n; j++) {
if(computers[i][j] == 1) {
union(i, j);
}
}
}
Set<Integer> set = new HashSet<>();
for(int i=0; i<n; i++) {
set.add(find(i));
}
return set.size();
30분