-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0547_findCircleNum.cc
85 lines (77 loc) · 1.33 KB
/
Problem_0547_findCircleNum.cc
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <vector>
using namespace std;
class Solution
{
public:
// TODO: bfs dfs
// 并查集
int findCircleNum(vector<vector<int>>& isConnected)
{
int n = isConnected.size();
UnionFind uf(n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (isConnected[i][j])
{
uf.unions(i, j);
}
}
}
return uf.size();
}
class UnionFind
{
vector<int> parent;
vector<int> sizes;
vector<int> help;
int number;
public:
UnionFind(int n)
{
parent.resize(n);
sizes.resize(n, 1);
help.resize(n);
for (int i = 0; i < n; i++)
{
parent[i] = i;
}
number = n;
}
int size() { return number; }
int find(int i)
{
int hi = 0;
while (i != parent[i])
{
help[hi++] = i;
i = parent[i];
}
for (hi--; hi >= 0; hi--)
{
parent[help[hi]] = i;
}
return i;
}
void unions(int i, int j)
{
int fi = find(i);
int fj = find(j);
if (fi != fj)
{
if (sizes[fi] >= sizes[fj])
{
parent[fj] = fi;
sizes[fi] += sizes[fj];
}
else
{
parent[fi] = fj;
sizes[fj] += sizes[fi];
}
number--;
}
}
};
};