In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.

The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N), with one additional directed 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] that represents a directed edge connecting nodes u and v, where u is a parent of child v.

Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.

Example 1:

Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
1
/ \
v v
2-->3

Example 2:

Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
^ |
| v
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.

这道题是之前那道 Redundant Connection 的拓展,那道题给的是无向图,只需要删掉组成环的最后一条边即可,归根到底就是检测环就行了。而这道题给的是有向图,整个就复杂多了,因为有多种情况存在,比如给的例子1就是无环,但是有入度为2的结点3。再比如例子2就是有环,但是没有入度为2的结点。其实还有一种情况例子没有给出,就是既有环,又有入度为2的结点。好,现在就来总结一下这三种情况:

第一种:无环,但是有结点入度为2的结点(结点3)

[[1,2], [1,3], [2,3]]

 / \
v v
-->

第二种:有环,没有入度为2的结点

[[1,2], [2,3], [3,4], [4,1], [1,5]]

 <-  ->
^ |
| v
<-

第三种:有环,且有入度为2的结点(结点1)

[[1,2],[2,3],[3,1],[1,4]]

    /
v / ^
v \
-->

对于这三种情况的处理方法各不相同,首先对于第一种情况,返回的产生入度为2的后加入的那条边 [2, 3],而对于第二种情况,返回的是刚好组成环的最后加入的那条边 [4, 1],最后对于第三种情况返回的是组成环,且组成入度为2的那条边 [3, 1]。

明白了这些,先来找入度为2的点,如果有的话,那么将当前产生入度为2的后加入的那条边标记为 second,前一条边标记为 first。然后来找环,为了方便起见,找环使用联合查找 Union Find 的方法,可参见 Redundant Connection 中的解法三。当找到了环之后,如果 first 不存在,说明是第二种情况,返回刚好组成环的最后加入的那条边。如果 first 存在,说明是第三种情况,返回 first。如果没有环存在,说明是第一种情况,返回 second,参见代码如下:

class Solution {
public:
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
int n = edges.size();
vector<int> root(n + , ), first, second;
for (auto& edge : edges) {
if (root[edge[]] == ) {
root[edge[]] = edge[];
} else {
first = {root[edge[]], edge[]};
second = edge;
edge[] = ;
}
}
for (int i = ; i <= n; ++i) root[i] = i;
for (auto& edge : edges) {
if (edge[] == ) continue;
int x = getRoot(root, edge[]), y = getRoot(root, edge[]);
if (x == y) return first.empty() ? edge : first;
root[x] = y;
}
return second;
}
int getRoot(vector<int>& root, int i) {
return i == root[i] ? i : getRoot(root, root[i]);
}
};

讨论:使用联合查找 Union Find 的方法一般都需要写个子函数,来查找祖宗结点,上面的解法 getRoot() 函数就是这个子函数,使用递归的形式来写的,其实还可以用迭代的方式来写,下面这两种写法都可以:

int getRoot(vector<int>& root, int i) {
while (i != root[i]) {
root[i] = root[root[i]];
i = root[i];
}
return i;
}
int getRoot(vector<int>& root, int i) {
while (i != root[i]) i = root[i];
return i;
}

Github 同步地址:

https://github.com/grandyang/leetcode/issues/685

类似题目:

Redundant Connection

Friend Circles

Accounts Merge

Number of Islands II

Graph Valid Tree

Number of Connected Components in an Undirected Graph

Similar String Groups

参考资料:

https://leetcode.com/problems/redundant-connection-ii/

https://leetcode.com/problems/redundant-connection-ii/discuss/108045/C++Java-Union-Find-with-explanation-O(n)

https://leetcode.com/problems/redundant-connection-ii/discuss/108058/one-pass-disjoint-set-solution-with-explain

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Redundant Connection II 冗余的连接之二的更多相关文章

  1. [LeetCode] 685. Redundant Connection II 冗余的连接之二

    In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...

  2. [LeetCode] 685. Redundant Connection II 冗余的连接之 II

    In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...

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

    In this problem, a tree is an undirected graph that is connected and has no cycles. The given input ...

  4. LeetCode 685. Redundant Connection II

    原题链接在这里:https://leetcode.com/problems/redundant-connection-ii/ 题目: In this problem, a rooted tree is ...

  5. [Swift]LeetCode685. 冗余连接 II | Redundant Connection II

    In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) f ...

  6. [LeetCode] Palindrome Permutation II 回文全排列之二

    Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empt ...

  7. [LeetCode] Arithmetic Slices II - Subsequence 算数切片之二 - 子序列

    A sequence of numbers is called arithmetic if it consists of at least three elements and if the diff ...

  8. [LeetCode] Contains Duplicate II 包含重复值之二

    Given an array of integers and an integer k, return true if and only if there are two distinct indic ...

  9. [LeetCode] Single Number II 单独的数字之二

    Given an array of integers, every element appears three times except for one. Find that single one. ...

随机推荐

  1. selenium2自动化测试学习笔记(三)

    今天是学习selenium的第三天,今天的主题是自动登录126邮箱. 今天总结碰到的坑有三个: 1.frame内元素抓取,使用driver.switch_to.frame(frameId)方法切换锁定 ...

  2. 记录python接口自动化测试--主函数(第六目)

    把操作excel的方法封装好后,就可以用准备好的接口用例来循环遍历了 我的接口测试用例如下 主函数代码: run_handle_excel.py# coding:utf-8 from base.run ...

  3. 《构建之法》教学笔记——Python中的效能分析与几个问题

    <构建之法:现代软件工程>中第2章对效能分析进行了介绍,基于的工具是VSTS.由于我教授的学生中只有部分同学选修了C#,若采用书中例子讲解,学生可能理解起来比较困难.不过所有这些学生都学习 ...

  4. 关于如何学习C语言

    2016级计算机专业的C语言分为两个学期,第一学期是C语言(基础),第二学期是C语言(高级),在第一学期主要学习的内容是基本的数据类型,分支结构和循环结构,一维和二维数组,字符数组,函数.通过这学期独 ...

  5. beta冲刺总结-咸鱼

    前言:emmmmmmm冲刺总结应该可以吐槽了?我发誓后面几篇冲刺我是很努力用正经语言描述了!!!!! 心得:emmmmm,说真的--到beta冲刺的时候才是真正感受到了组队的存在,基本上隔三差五就约一 ...

  6. C语言第二周作业----分支结构

    一.PTA实验作业 题目1.7-1计算分段函数 本题目要求计算下列分段函数f(x)的值: 注:可在头文件中包含math.h,并调用sqrt函数求平方根,调用pow函数求幂. 1.实验代码 int ma ...

  7. Flask 扩展 自定义扩展

    创建一个为视图访问加日志的扩展Flask-Logging,并从中了解到写Flask扩展的规范. 创建工程 先创建一个工程,目录结构如下: flask-logging/ ├ LICENSE # 授权说明 ...

  8. android头像选择(拍照,相册,裁剪)

    组织头像上传时候,不兼容android6.0,并且 imageview.setImageBitmap(BitmapFactory.decodeFile(IMAGE_FILE_LOCATION));// ...

  9. 201621123027 《Java程序设计》第1周学习总结

    01621123027 <Java程序设计>第1周学习总结 1.本周学习总结 关键词:总概.承接.面向对象化 ​ 我认为第一周的Java学习是一些总结概括性质的内容,在比较联系之前学习过的 ...

  10. 接触JS的变量

    刚刚接触到js,写的代码都是很简单的,制单的概念也相当少,新学习的就是变量.let和const以及js的数据类型. 变量的内容有五个,我就不一一介绍了,重点在于: 在 JavaScript 中,使用变 ...