题目
Redundant Connection
难度 Medium
In this problem, a tree is an undirected graph that is connected and has no cycles.
The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v.
Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be like this:
1
/ \
2 - 3
Example 2:
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be like this:
5 - 1 - 2
| |
4 - 3
Note:
The size of the input 2D-array will be between 3 and 1000.
Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.Update (2017-09-26):
We have overhauled the problem description + test cases and specified clearly the graph is an undirected graph. For the directed graph follow up please see Redundant Connection II). We apologize for any inconvenience caused.
实现思路
可以利用UnionSet的思想实现,相当于把结点分组,两个结点连通则分到同一组。初始时每个点自成一组,当加入一条(i,j)边时,把i和j放到同一组。假设最开始只有一条(0,1)的边,那么把0和1分到同一组,再加入一条(1,2)的边,因为0与1相连,因此0和2也有一条边,把0,1,2分到一组。使用组号标记他们是哪一组,此处组号都设为2,先把0分到组1,再把组1分到组2。当加入新的边(0,2)时,由于他们是同一组,说明没有这条边之前他们已经连通,因此这条边是冗余的。
实现时建立一个UnionSet的数组,每个值初始化为下标号。当加入一条边时就将查看边的两个结点的分组,如果分组一样就是冗余,否则将他们分到同一组。
实现代码
//分组
int find(vector<int>& unionSet, int w) {
while (unionSet[w] != w) {
w = unionSet[w];
}
return w;
}
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
vector<int> unionSet(2001,0);
for (int i = 1; i < 2001; i++) {
unionSet[i] = i;
}
for (int i = 0; i < edges.size(); i++) {
if (find(unionSet, edges[i][0]) != find(unionSet,edges[i][1])) {
unionSet[find(unionSet, edges[i][0])] = find(unionSet, edges[i][1]);
} else {
return edges[i];
}
}
return {};
}