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.

684. Redundant Connection 的拓展,684题给的是无向图,只需要删掉组成环的最后一条边即可,检测环就行了。这题给的是有向图,就复杂多了,有多种情况存在,比如例子1就是无环,但是有入度为2的结点3。再比如例子2是有环,但是没有入度为2的结点。还有一种情况例子没有给出,就是既有环,又有入度为2的结点。

解法:Union find

There are two cases for the tree structure to be invalid.
1) A node having two parents;
including corner case: e.g. [[4,2],[1,5],[5,2],[5,3],[2,4]]
2) A circle exists

If we can remove exactly 1 edge to achieve the tree structure, a single node can have at most two parents.

1) Check whether there is a node having two parents.
If so, store them as candidates A and B, and set the second edge invalid.
2) Perform normal union find.

If the tree is now valid
    simply return candidate B
else if candidates not existing
    we find a circle, return current edge;
else
    remove candidate A instead of B.

Java:

class Solution {
public int[] findRedundantDirectedConnection(int[][] edges) {
int[] can1 = {-1, -1};
int[] can2 = {-1, -1};
int[] parent = new int[edges.length + 1];
for (int i = 0; i < edges.length; i++) {
if (parent[edges[i][1]] == 0) {
parent[edges[i][1]] = edges[i][0];
} else {
can2 = new int[] {edges[i][0], edges[i][1]};
can1 = new int[] {parent[edges[i][1]], edges[i][1]};
edges[i][1] = 0;
}
}
for (int i = 0; i < edges.length; i++) {
parent[i] = i;
}
for (int i = 0; i < edges.length; i++) {
if (edges[i][1] == 0) {
continue;
}
int child = edges[i][1], father = edges[i][0];
if (root(parent, father) == child) {
if (can1[0] == -1) {
return edges[i];
}
return can1;
}
parent[child] = father;
}
return can2;
} int root(int[] parent, int i) {
while (i != parent[i]) {
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
}

Python:

# Time:  O(nlog*n) ~= O(n), n is the length of the positions
# Space: O(n)
class UnionFind(object):
def __init__(self, n):
self.set = range(n)
self.count = n def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x] def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root == y_root or \
y != y_root: # already has a father
return False
self.set[y_root] = x_root
self.count -= 1
return True class Solution(object):
def findRedundantDirectedConnection(self, edges):
"""
:type edges: List[List[int]]
:rtype: List[int]
"""
union_find = UnionFind(len(edges)+1)
for edge in edges:
if not union_find.union_set(*edge):
return edge
return []  

C++:

class Solution {
public:
vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) {
int n = edges.size();
vector<int> parent(n+1, 0), candA, candB;
// step 1, check whether there is a node with two parents
for (auto &edge:edges) {
if (parent[edge[1]] == 0)
parent[edge[1]] = edge[0];
else {
candA = {parent[edge[1]], edge[1]};
candB = edge;
edge[1] = 0;
}
}
// step 2, union find
for (int i = 1; i <= n; i++) parent[i] = i;
for (auto &edge:edges) {
if (edge[1] == 0) continue;
int u = edge[0], v = edge[1], pu = root(parent, u);
// Now every node only has 1 parent, so root of v is implicitly v
if (pu == v) {
if (candA.empty()) return edge;
return candA;
}
parent[v] = pu;
}
return candB;
}
private:
int root(vector<int>& parent, int k) {
if (parent[k] != k)
parent[k] = root(parent, parent[k]);
return parent[k];
}
};

 

类似题目:

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

All LeetCode Questions List 题目汇总

[LeetCode] 685. Redundant Connection II 冗余的连接之 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

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

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

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

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

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

  5. LN : leetcode 684 Redundant Connection

    lc 684 Redundant Connection 684 Redundant Connection In this problem, a tree is an undirected graph ...

  6. LeetCode 684. Redundant Connection 冗余连接(C++/Java)

    题目: In this problem, a tree is an undirected graph that is connected and has no cycles. The given in ...

  7. leetcode 684. Redundant Connection

    We are given a "tree" in the form of a 2D-array, with distinct values for each node. In th ...

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

    Leetcode之并查集专题-684. 冗余连接(Redundant Connection) 在本问题中, 树指的是一个连通且无环的无向图. 输入一个图,该图由一个有着N个节点 (节点值不重复1, 2 ...

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

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

随机推荐

  1. MacOS查看NGINX文件路径(配置文件、日志文件)

    使用 MacOS 经常发现 NGINX 路径不好找,后来发现一个很好的命令来查找: nginx -V 即可输出 NGINX 各文件夹的路径.

  2. Java 出现cannot be resolved to a type

    package com.sysutil.util; /* thishi duo zhu */ // dan zhshi import com.sysutil.util.*; class Example ...

  3. oracle数据库(四)

    子查询与高级查询 我们在检索数据库的时候,需要将多个表关联起来进行查询,最常用的有子查询.连接查询和集合查询,子查询可以从另外一个表获取数据,连接查询可以指定多个表的连接方式,集合查询可以将两个或者多 ...

  4. modbus-poll和modbus-slave工具的学习使用——modbus协议功能码1的解析

    一.数据解析 上一文介绍了modbus工具的基本使用情况,但是还没用说明modbus中的协议的具体意义, 1.左边是slave,id=1,说明地址是1,f=01说明是功能码01,功能码是一个字节,说明 ...

  5. robot framework 特点及安装方法

    最近准备给组内成员分享一下前一个项目组所用到的一个接口自动化测试框架-robot framework,所以又稍微整理了一下,顺便也给大家分享一下. 一:特点 1.robot framework 是py ...

  6. MATLAB中运算符优先级

    下述运算符的优先级从低到高: 1.先决或(||): 2.先决与(&&): 3.逻辑或(|): 4.逻辑与(&): 5.等于类(<,<=,>,>=,==, ...

  7. js 键盘事件(onkeydown、onkeyup、onkeypress)

    onkeypress 这个事件在用户按下并放开任何字母数字键时发生.系统按钮(例如,箭头键和功能键)无法得到识别. onkeyup 这个事件在用户放开任何先前按下的键盘键时发生. onkeydown ...

  8. 检验多个xsd的xml是否合法

    Java - 使用 XSD 校验 XML https://www.cnblogs.com/huey/p/4600817.html 这种方法不支持多个xsd文件,会报错 可以使用XMLBeans Too ...

  9. 浅谈H5图片中object-fit的属性及含义/ 小程序image mode属性中scaleToFill,aspectFit,widthFix等类似

    我们在H5中对于图片的属性包含如下: object-fit属性有哪些值呢? object-fit: fill;  object-fit: contain;  object-fit: cover;  o ...

  10. virtualenvwrapper 方便的virtualenv 包装

      virtualenvwrapper 是一个方便的virtualenv 包装我们可以用来方便的管理python 的开发环境,同时 也支持对于项目的管理 安装 pip 安装 pip install v ...