Skip to content

Commit a81f33a

Browse files
Merge pull request #109 from IamSohamDey/patch-5
Create FriendCircles.java
2 parents 113771c + 30e7024 commit a81f33a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

FriendCircles.java

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
class UnionFind {
2+
private int[] parents;
3+
private int circleCount;
4+
5+
public UnionFind(int n) {
6+
parents = new int[n];
7+
for (int i = 0; i < n; i++) {
8+
parents[i] = i;
9+
}
10+
}
11+
12+
public int find(int x) {
13+
if (parents[x] == x) {
14+
return x;
15+
}
16+
17+
return parents[x] = find(parents[x]);
18+
}
19+
20+
public void union(int a, int b) {
21+
int groupA = find(a);
22+
int groupB = find(b);
23+
24+
if (groupA != groupB) {
25+
parents[groupA] = groupB;
26+
circleCount--;
27+
}
28+
}
29+
30+
public void setCircleCount(int circleCount) {
31+
this.circleCount = circleCount;
32+
}
33+
34+
public int getCircleCount() {
35+
return this.circleCount;
36+
}
37+
}
38+
39+
class Solution {
40+
public int findCircleNum(int[][] M) {
41+
if (M.length == 0 || M[0].length == 0) {
42+
return 0;
43+
}
44+
45+
int m = M.length;
46+
int n = M[0].length;
47+
48+
UnionFind unionFind = new UnionFind(m * n);
49+
unionFind.setCircleCount(m);
50+
51+
for (int i = 0; i < m; i++) {
52+
for (int j = 0; j < n; j++) {
53+
if (M[i][j] == 1 && i != j) {
54+
unionFind.union(i, j);
55+
}
56+
}
57+
}
58+
59+
return unionFind.getCircleCount();
60+
}
61+
}

0 commit comments

Comments
 (0)