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
寻找多余的连接线。
用Union-Find,把所有的点归类。
1 class Solution { 2 public: 3 int Find(vector<int> &belong, int key) { 4 while (belong[key] != key) 5 key = belong[key]; 6 return key; 7 } 8 void Union(vector<int> &belong, int p1, int p2) { 9 belong[Find(belong, p2)] = p1; 10 } 11 vector<int> findRedundantConnection(vector<vector<int>>& edges) { 12 int len = edges.size(); 13 vector<int> belong; 14 vector<int> res; 15 for (int i=0; i<=len; ++i) 16 belong.push_back(i); 17 for (auto &pot: edges) { 18 int p1 = pot[0]; 19 int p2 = pot[1]; 20 if (Find(belong, p1) == Find(belong, p2)) 21 res.insert(res.end(), pot.begin(), pot.end()); 22 else 23 Union(belong, p1, p2); 24 } 25 return res; 26 } 27 };