Inthis problem, a tree is an undirected graph that is connected and has no cycles.
Thegiven input is a graph that started as a tree with N nodes (with distinctvalues 1, 2, ..., N), with one additional edge added. The added edge has twodifferent vertices chosen from 1 to N, and was not an edge that alreadyexisted.
Theresulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents anundirected edge connecting nodes u and v.
Returnan 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 given2D-array. The answer edge [u, v] should be in the same format, with u < v.
Example1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given undirected graph will be likethis:
1
/ \
2 - 3
Example2:
Input: [[1,2], [2,3], [3,4], [1,4], [1,5]]
Output: [1,4]
Explanation: The given undirected graph will be likethis:
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, whereN is the size of the input array.
Update(2017-09-26):
We have overhauled the problem description + test cases and specified clearlythe graph is an undirected graph. For the directedgraph follow up please see Redundant Connection II). We apologize for any inconvenience caused.
这是一道妥妥的拓扑排序题
题目给你一颗树,然后向这颗树里面假如一条边,那么这颗树一定会形成一个环,且只会形成这一个环,题目让你除掉一条边,使得有环的图重新变成无环的图,也就是树,其实只要除掉环里面的任意一条边就能达到这个要求,并且这题要求输出最后一条输入的边,但是我们需要知道哪些边在环里面,哪条边是最后一个输入的
首先建立一个数组theCount[i]用来存储编号为i的节点的出度,对theCount[i]使用拓扑排序,每次遍历除掉出度为1的边,直到theCount里面不存在出度为1的边,剩下的边一定是环里面的边,然后从后往前遍历edges,得到的第一条在环里面的边,就是需要的结果
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
int n = edges.size(); int a, b;
vector<vector<int>> theEdges(n + 2);
vector<int> theCount(n + 2, 0);
for (int i = 0; i < n; i++)
{
a = edges[i][0]; b = edges[i][1];
theEdges[a].push_back(b);
theCount[a]++;
theEdges[b].push_back(a);
theCount[b]++;
}
bool found = false;
int mark;
while (1)
{
found = false;
for (int i = 0; i < theCount.size(); i++)
{
if (theCount[i] == 1)
{
found = true;
theCount[i]--;
for (int j = 0; j < theEdges[i].size(); j++)
{
theCount[theEdges[i][j]]--;
}
}
}
if (!found) break;
}
vector<int> result;
for (int i = n - 1; i >= 0; i--)
{
if (theCount[edges[i][0]] > 1 && theCount[edges[i][1]] > 1)
{
result.push_back(edges[i][0]);
result.push_back(edges[i][1]);
break;
}
}
return result;
}
};