-
Notifications
You must be signed in to change notification settings - Fork 90
Expand file tree
/
Copy pathFriendCircles.java
More file actions
61 lines (49 loc) · 1.39 KB
/
FriendCircles.java
File metadata and controls
61 lines (49 loc) · 1.39 KB
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
51
52
53
54
55
56
57
58
59
60
61
class UnionFind {
private int[] parents;
private int circleCount;
public UnionFind(int n) {
parents = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
}
}
public int find(int x) {
if (parents[x] == x) {
return x;
}
return parents[x] = find(parents[x]);
}
public void union(int a, int b) {
int groupA = find(a);
int groupB = find(b);
if (groupA != groupB) {
parents[groupA] = groupB;
circleCount--;
}
}
public void setCircleCount(int circleCount) {
this.circleCount = circleCount;
}
public int getCircleCount() {
return this.circleCount;
}
}
class Solution {
public int findCircleNum(int[][] M) {
if (M.length == 0 || M[0].length == 0) {
return 0;
}
int m = M.length;
int n = M[0].length;
UnionFind unionFind = new UnionFind(m * n);
unionFind.setCircleCount(m);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (M[i][j] == 1 && i != j) {
unionFind.union(i, j);
}
}
}
return unionFind.getCircleCount();
}
}