684. Redundant Connection 找到成环的那条边

684. Redundant Connection 找到成环的那条边_第1张图片
image.png

如果两个顶点已经是连通状态,那么再连起来,就会形成一个环
使用到并查集

class Solution {
public:
    vector findRedundantConnection(vector>& edges) {
        int N = edges.size();
        vector res(2);
        int parent[1001] = {};
        for(int i = 0; i < N; i++){
            parent[i] = i;
        }
        for(int i = 0; i < N; i++){
            int u = edges[i][0];
            int v = edges[i][1];
            if(findparent(parent, u) == findparent(parent,v)){
                res[0] = u;
                res[1] = v;
                return res;
            }
            else{
                parent[findparent(parent, u)] = findparent(parent,v);
            }
        }
        return res;
        
    }
private:
    int findparent(int parent[], int root){
        int son = root;
        while(root != parent[root])
            root = parent[root];
        while(son != parent[son]){
            int tmp = son;
            son = parent[son];
            parent[tmp] = root;
            
        }
        return root;
    }
};

你可能感兴趣的:(684. Redundant Connection 找到成环的那条边)