-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMain.java
50 lines (37 loc) Β· 1.04 KB
/
Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package Graph.prg43162;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.solution(3, new int[][]{{1, 1, 0}, {1, 1, 0}, {0, 0, 1}}));
System.out.println(sol.solution(3, new int[][]{{1, 1, 0}, {1, 1, 1}, {0, 1, 1}}));
}
}
// 1 1 0
// 1 1 0
// 0 0 1
// 1 1 0
// 1 1 1
// 0 1 1
class Solution {
static int[] root;
public int solution(int n, int[][] computers) {
root = new int[n];
for (int i = 0; i < n; i++) root[i] = i;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (computers[i][j] == 1) merge(i, j);
}
}
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) set.add(find(i));
return set.size();
}
static int find(int n) {
if (root[n] == n) return n;
return root[n] = find(root[n]);
}
static void merge(int a, int b) {
root[find(b)] = find(a);
}
}