leetcode547 省份数量
题目可见:https://leetcode-cn.com/problems/number-of-provinces/
很明显是一个并查集,上模版即可:
class Solution {
public:
int findCircleNum(vector<vector<int>>& isConnected) {
init(isConnected.size());
for(int i =0 ; i < isConnected.size(); i++) {
for(int j = i+1; j < isConnected[i].size(); j++) {
if(isConnected[i][j]) merge(i,j);
}
}
int ans = 0;
for(int i = 0; i < isConnected.size(); i++) {
if(p[i]==i) ans++;
}
return ans;
}
private:
int p[210];
void init(int n){
for(int i=0;i<n;i++) {
p[i] = i;
}
}
int find(int x) {
if(p[x] != x) p[x] = find(p[x]);
return p[x];
}
void merge(int a, int b){
a = find(a);
b = find(b);
p[a] = b;
}
};