【LeetCode】684. Redundant Connection
来源:互联网 发布:南京奥派软件 编辑:程序博客网 时间:2024/06/07 07:40
问题描述
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
.
Input: [[1,2], [1,3], [2,3]]Output: [2,3]Explanation: The given undirected graph will be like this: 1 / \2 - 3
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:
思路
判断无向图是否有环有几种方法:
若所有点中只有一个点的根节点是他本身,则根节点入度为0。
第二步:将度数变为1的顶点排入队列,并从该队列中取出一个顶点重复步骤一。
如果最后还有未删除顶点,则存在环,否则没有环。
int findParent(vector<int>& parent, int k) { if (parent[k] != k) parent[k] = findParent(parent, parent[k]); return parent[k];}vector<int> findRedundantConnection(vector<vector<int> >& edges) {vector<int> parent; for (int i = 0; i < 2001; i++) // 初始化 parent.push_back(i); int point1, point2; for (int j = 0; j < edges.size(); j++) { point1 = findParent(parent, edges[j][0]); point2 = findParent(parent, edges[j][1]); if (point1 == point2) return edges[j]; parent[point2] = point1; } return vector<int>(0, 0);}
- leetcode 684. Redundant Connection
- 【LeetCode】684. Redundant Connection
- [LeetCode]684. Redundant Connection
- leetcode 684. Redundant Connection解法
- LeetCode 684. Redundant Connection [Medium]
- LeetCode题解系列--684. Redundant Connection
- Redundant Connection(leetcode)
- 【LeetCode】Redundant Connection
- leetcode练习 Redundant Connection
- leetcode Redundant Connection
- LeetCode #684 Redundant Connection
- [LeetCode]685. Redundant Connection II
- 684. Redundant Connection
- 684. Redundant Connection
- 684. Redundant Connection
- 684. Redundant Connection
- 684. Redundant Connection
- 684. Redundant Connection
- C++ 函数模板和类模板简单总结一下
- Solr的安装配置
- [BZOJ4518][SDOI2016]征途(斜率优化DP)
- Ubuntu,python 3默认修改
- 英语之冠词规则
- 【LeetCode】684. Redundant Connection
- UVa1637
- R语言之函数与包
- u-boot-2017.07移植到S5PV210单板
- GIT学习笔记(3)
- git add -u与-A .三者的区别
- 跟我一起学Keras之实例篇(2)
- WebView基础三:WebView优化
- 深入理解java虚拟机—虚拟机字节码执行引擎