-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0547_Number_of_Provinces.java
55 lines (45 loc) · 1.14 KB
/
0547_Number_of_Provinces.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
53
54
55
/*
* 547. Number of Provinces
* Problem Link: https://leetcode.com/problems/number-of-provinces/
* Difficulty: Medium
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
// Union Find Approach
class Solution {
int [] p;
public int find(int x) {
if (p[x] == x)
return x;
return p[x] = find(p[x]);
}
public boolean union (int x, int y) {
x = find(x);
y = find(y);
if (x != y) {
p[x] = y;
return true;
}
return false;
}
public int findCircleNum(int[][] isConnected) {
int n = isConnected.length;
int count = n;
p = new int [n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++ ){
if (isConnected[i][j] == 1) {
if (union(i, j))
count--;
}
}
}
return count;
}
}