-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
44 lines (38 loc) · 1.02 KB
/
Solution.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
package L547;
public class Solution {
private int[] fa;
int find(int x) {
if (x == fa[x])
return x;
return fa[x] = find(fa[x]);
}
void UnionSet(int x, int y) {
x = find(x);
y = find(y);
if (x != y)
fa[x] = y;
}
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
fa = new int[n];
for (int i = 0; i < n; i++)
fa[i] = i;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (isConnected[i][j] == 1)
UnionSet(i, j);
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (find(i) == i)
ans++;
}
return ans;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[][] isConnected = { { 1, 1, 0 }, { 1, 1, 0 }, { 0, 0, 1 } };
System.out.println(solution.findCircleNum(isConnected));
}
}