Skip to content

Commit 8e8a182

Browse files
committed
fd
1 parent 69481da commit 8e8a182

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

leetcode/solution/src/FriendCircles.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,47 @@ private void dfs(int[][] M, int i) {
2323
}
2424
}
2525
}
26+
27+
public int findCircleNum2(int[][] M) {
28+
int n = M.length;
29+
UnionFind uf = new UnionFind(n);
30+
for (int i = 0; i < n; i++) {
31+
for (int j = i + 1; j < n; j++) {
32+
if (M[i][j] == 1) {
33+
uf.union(i, j);
34+
}
35+
}
36+
}
37+
return uf.count();
38+
}
39+
40+
class UnionFind {
41+
int[] path;
42+
int count;
43+
44+
public UnionFind(int n) {
45+
path = new int[n];
46+
count = n;
47+
for (int i = 0; i < n; i++) {
48+
path[i] = i;
49+
}
50+
}
51+
52+
public int find(int i) {
53+
while (i != path[i]) i = path[i];
54+
return i;
55+
}
56+
57+
public void union(int i, int j) {
58+
int rootI = find(i);
59+
int rootJ = find(j);
60+
if (rootI == rootJ) return;
61+
path[rootI] = rootJ;
62+
count--;
63+
}
64+
65+
public int count() {
66+
return count;
67+
}
68+
}
2669
}

0 commit comments

Comments
 (0)