并查集(Union-Find)模板

并查集模板,题目来自力扣547.朋友圈

class Solution {
     
private: 
//并查集模板
    vector<int> pre;
    int Find(int a) {
     
        int r = a;
        if (pre[r] == r)
            return r;
        return Find(pre[r]);
    }
    void Union(int a, int b) {
     
        int pa = Find(a);
        int pb = Find(b);
        if (pa == pb)
            return;
        pre[pa] = pb;
    }
public:
    int findCircleNum(vector<vector<int>>& M) {
     
        const int N = M.size();
        for(int i=0;i < N; ++i)
        {
     
            pre.push_back(i);
        }
        for(int i = 0; i < N;++i)
        {
     
            for(int j = i+1; j < N; ++j)
            {
     
                if(M[i][j])
                    Union(i,j);
            }
        }
        int res = 0;
        for(int i = 0; i < N; ++i)
        {
     
            if(pre[i] == i)
                res++;
        }
        return res;
    }
};

你可能感兴趣的:(C++算法,c++)