并查集总结

并查集基本操作:

union + find

 

解法1: 并查集

 

class Solution {
public:
    /**
     * @param n: An integer
     * @param edges: a list of undirected edges
     * @return: true if it's a valid tree, or false
     */
    bool validTree(int n, vector<vector<int>> &edges) {
        // write your code here
        //union find
        vector<int> parent(n, -1);
        for(int i=0; i<edges.size(); i++){
            //union
            int p1 = find(edges[i][0], parent);
            int p2 = find(edges[i][1], parent);
            if(p1 == p2)
                return false;   //存在环
            parent[p2] = p1;
        }
        return edges.size() == n-1;  //树中若有n个点,则一定有n-1条边
    }
    
    //find
    int find(int e, vector<int> p){
        if(p[e] == -1)
            return e;
        else
            return p[e] = find(p[e], p);
    }
};

 

解法二: BFS

 

posted @ 2019-08-29 16:26  爱学英语的程序媛  阅读(226)  评论(0编辑  收藏  举报