-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path547.cpp
More file actions
51 lines (51 loc) · 1.21 KB
/
547.cpp
File metadata and controls
51 lines (51 loc) · 1.21 KB
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
class DisjointSet {
private:
vector<int> parents;
vector<int> ranks;
int nodes;
public:
DisjointSet(int size) {
this->nodes = size;
parents.resize(size, 0);
ranks.resize(size, 0);
for (int i = 0; i < size; ++i) parents[i] = i;
}
int find(int x) {
if (parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
void join(int x, int y) {
int pX = find(x);
int pY = find(y);
if (pX == pY) return;
nodes--;
if (ranks[pY] > ranks[pX]) {
parents[pX] = pY;
}
else if (ranks[pY] < ranks[pX]) {
parents[pY] = pX;
}
else {
parents[pY] = pX;
ranks[pX]++;
}
}
int getNodes() {
return nodes;
}
};
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
DisjointSet* disjointSet = new DisjointSet(n);
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (isConnected[i][j]) disjointSet->join(i, j);
}
}
return disjointSet->getNodes();
}
};