684. Redundant Connection

Posted Zzz...y

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了684. Redundant Connection相关的知识,希望对你有一定的参考价值。

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 };

 

以上是关于684. Redundant Connection的主要内容,如果未能解决你的问题,请参考以下文章

684. Redundant Connection

684. Redundant Connection

684. Redundant Connection

Graph-684. Redundant Connection

[LeetCode] 684. Redundant Connection 冗余的连接

Leetcode之并查集专题-684. 冗余连接(Redundant Connection)