forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_547.java
52 lines (45 loc) · 1.36 KB
/
_547.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
51
52
package com.fishercoder.solutions;
public class _547 {
public static class Solution1 {
public int findCircleNum(int[][] M) {
if (M == null || M.length == 0 || M[0].length == 0) {
return 0;
}
int m = M.length;//number of rows in this matrix
UnionFind unionFind = new UnionFind(m);
for (int i = 0; i < m; i++) {
for (int j = i + 1; j < m; j++) {
if (M[i][j] == 1) {
unionFind.union(i, j);
}
}
}
return unionFind.count;
}
class UnionFind {
int count;
int[] root;
public UnionFind(int m) {
root = new int[m];
for (int i = 0; i < m; i++) {
root[i] = i;
}
count = m;
}
public void union(int i, int j) {
int x = find(root, i);
int y = find(root, j);
if (x != y) {
count--;
root[x] = y;//path compression
}
}
public int find(int[] ids, int i) {
if (ids[i] == i) {
return i;
}
return find(ids, ids[i]);
}
}
}
}