题目描述
前言:在这个问题中,树的定义是无向且无环的。
现在给你一个图,在这个图中存在一条多余的边,去掉那一条边后,这个图边符合树的定义,现在我们要做的就是找出那一条多余的边。如果有多条边符合条件,那么则返还最后出现的那条边。原题以及例子如下,
算法描述
这里我们通过每次加入一条边,直到环的出现,来得出答案,使得环出现的那条边必然是最后一个符合条件的边。在判断是否成环时可以使用并查集来快速查找其根节点。代码如下,
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
node.resize(1000);
for (int i = 1; i <= 1000; ++i) {
node[i] = i;
}
for (int i = 0; i < edges.size(); ++i) {
int fir = edges[i][0], sec = edges[i][1];
cout << fir << " " << sec << endl;
if (unio(fir, sec)) {
cout << fir << " " << sec << endl;
vector<int> ans(2, 0);
ans[0] = fir;
ans[1] = sec;
return ans;
}
}
}
private:
vector<int> node;
vector<int> height;
int findRoot(int i) {
while (i != node[i]) {
node[i] = node[node[i]];
i = node[i];
}
return i;
}
bool unio(int i, int j) {
int x = findRoot(i);
int y = findRoot(j);
if (x == y) {
return true;
} else {
node[y] = x;
}
return false;
}
};