原题链接:Lecode 684. 冗余连接 并查集
class Solution {
public:
map<int,int> father;
int findfather(int x)
{
if(father[x]==x) return x;
else return findfather(father[x]);
}
void Union(int x,int y)
{
int fx=findfather(x);
int fy=findfather(y);
if(fx!=fy) father[fx]=fy;
}
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n=edges.size();
for(int i=1;i<=n;i++) father[i]=i;
for(int i=0;i<n;i++)
{
int x=edges[i][0];
int y=edges[i][1];
if(findfather(x)!=findfather(y)) Union(x,y);
else return {x,y};
}
return {};
}
};
|