美文网首页
684. Redundant Connection 找到成环的那

684. Redundant Connection 找到成环的那

作者: 刘小小gogo | 来源:发表于2018-09-23 17:01 被阅读0次
image.png

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

class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        int N = edges.size();
        vector<int> 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 找到成环的那

      本文链接:https://www.haomeiwen.com/subject/sohqoftx.html