Skip to content

Commit 3a0c644

Browse files
committed
Two-Hundred-Thirty-One Commit: Add Number of Provinces problem to Union Find Section
1 parent 209e177 commit 3a0c644

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package Union_Find;
2+
3+
// Problem Statement: Number of Provinces (medium)
4+
// LeetCode Question: 547. Number of Provinces
5+
6+
public class Problem_2_Number_Of_Provinces {
7+
private int[] parent;
8+
9+
public int findProvinces(int[][] isConnected){
10+
int n = isConnected.length;
11+
parent = new int[n];
12+
for (int i = 0; i < n; i++) {
13+
parent[i] = i;
14+
}
15+
int provinces = n;
16+
for (int i = 0; i < n; i++) {
17+
for (int j = i + 1; j < n; j++) {
18+
if (isConnected[i][j] == 1 && find(i) != find(j)) {
19+
union(i, j);
20+
provinces--;
21+
}
22+
}
23+
}
24+
return provinces;
25+
}
26+
27+
private int find (int i) {
28+
if (parent[i] != i) {
29+
parent[i] = find(parent[i]);
30+
}
31+
return parent[i];
32+
}
33+
34+
private void union (int i, int j) {
35+
parent[find(i)] = find(j);
36+
}
37+
}

0 commit comments

Comments
 (0)