如果两个顶点已经是连通状态,那么再连起来,就会形成一个环
使用到并查集,
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;
}
};
网友评论