并查集
547. 省份数量 - 力扣(LeetCode) (leetcode-cn.com)
1 class Solution { 2 public: 3 vector<int>father; 4 int find(int x){ 5 if(father[x]==x) 6 return x; 7 return find(father[x]); 8 } 9 void tunion(int a,int b){ 10 father[find(b)] = find(a); 11 } 12 int findCircleNum(vector<vector<int>>& isConnected) { 13 int n = isConnected.size(); 14 father = vector<int>(n); 15 for (int i=0;i<n;i++){ 16 father[i] = i; 17 for (int j=0;j<i;j++){ 18 if(isConnected[i][j] == 1){ 19 tunion(j,i); 20 } 21 } 22 } 23 vector<int>vis(n,0); 24 int ans = 0; 25 for(int i=0;i<n;i++){ 26 if(vis[i] == 1) 27 continue ; 28 ans++;vis[i] = 1; 29 for(int j=i+1;j<n;j++){ 30 if(find(i) == find(j)){ 31 vis[j] = 1; 32 } 33 } 34 } 35 return ans; 36 } 37 };
find那里可以递归也可以while循环
union那里在函数里找祖先也可以在主函数里找祖先
我这边习惯主函数简洁