Skip to content

Commit 9335563

Browse files
committed
Update 547_Number_of_Provinces.java
1 parent b34aa03 commit 9335563

File tree

2 files changed

+58
-67
lines changed

2 files changed

+58
-67
lines changed

Graphs/47_Number_of_Provinces.java

Lines changed: 0 additions & 67 deletions
This file was deleted.

Graphs/547_Number_of_Provinces.java

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
public int findCircleNum(int[][] isConnected) {
3+
UnionFind uf = new UnionFind(isConnected.length);
4+
5+
for (int row = 0; row < isConnected.length; row++) {
6+
for (int col = 0; col < isConnected[row].length; col++) {
7+
if (isConnected[row][col] == 1) {
8+
uf.union(row, col);
9+
}
10+
}
11+
}
12+
13+
return uf.noOfComponents;
14+
}
15+
16+
private class UnionFind {
17+
private int[] parents, counts;
18+
private int noOfComponents;
19+
20+
public UnionFind(int n) {
21+
noOfComponents = n;
22+
parents = new int[n];
23+
counts = new int[n];
24+
25+
for (int i = 0; i < parents.length; i++) {
26+
parents[i] = i;
27+
counts[i] = 1;
28+
}
29+
}
30+
31+
public int find(int node) {
32+
if (parents[node] == node) {
33+
return node;
34+
}
35+
36+
parents[node] = find(parents[parents[node]]);
37+
return parents[node];
38+
}
39+
40+
public void union(int i, int j) {
41+
int p1 = find(i), p2 = find(j);
42+
43+
if (p1 == p2) {
44+
return;
45+
}
46+
47+
if (counts[p1] > counts[p2]) {
48+
parents[p2] = p1;
49+
counts[p1] += counts[p2];
50+
} else {
51+
parents[p1] = p2;
52+
counts[p2] += counts[p1];
53+
}
54+
55+
--noOfComponents;
56+
}
57+
}
58+
}

0 commit comments

Comments
 (0)