leetcode_684. Redundant Connection

https://leetcode.com/problems/redundant-connection/

一个无向图,n个顶点有n条边,输出一条可以删除的边,删除后使得图成为一棵树。可以使用并查集解决。

class Solution
{
public:
    int father[1001];
    void initfather()
    {
        for(int i=1; i<=1000; i++)
            father[i]=i;
    }

    int findFather(int x)
    {
        if(father[x]!=x)
            father[x] = findFather(father[x]);
        return father[x];
    }

    void Merge(int x1, int x2)
    {
        int father_x1 = findFather(x1);
        int father_x2 = findFather(x2);
        if(father_x1 != father_x2)
            father[father_x2] = father_x1;
    }

    vector<int> findRedundantConnection(vector<vector<int>>& edges)
    {
        initfather();
        vector<int> res;
        for(auto edge:edges)
        {
            int u = edge[0];
            int v = edge[1];
            if(findFather(u) == findFather(v))
            {
                res=edge;
                break;
            }
            else
                Merge(u,v);
        }
        return res;
    }
};

 

posted on 2019-04-12 14:17  JASONlee3  阅读(96)  评论(0编辑  收藏  举报

导航