Redundant Connection II

Tree, Depth-first Search, Union Find, Graph

Hard

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 ofedges. Each element ofedgesis a pair[u, v]that represents adirectededge connecting nodesuandv, whereuis a parent of childv.

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.

Analysis

Redundant Connection 那道题给的是无向图,只需要删掉组成环的最后一条边即可,归根到底就是检测环就行了。而这道题给我们的是有向图,那么整个就复杂多了,因为有多种情况存在 via @Grandyang

From: @cherryljr/LeetCode/Redundant Connection II.java

本题中使得树 invalid 的情况总共有 1+2=3 种。

因此当我们遇到某个节点有 两个父亲节点 的情况时,我们需要删除的是:

  • 如果没有环,删除 最后一次遇到存在两个父亲的节点 的边;

  • 如果有环,删除 环中存在两个父亲的节点 的边。

Time complexity: O(nlog*n) ~ O(n)

Space complexity: O(n)

Solution

Union Find

Based on 李同学's:

Reference

https://www.youtube.com/watch?v=lnmJT5b4NlM&t=2s

http://zxi.mytechroad.com/blog/graph/leetcode-685-redundant-connection-ii/

https://github.com/cherryljr/LeetCode/blob/master/Redundant Connection II.java

http://www.cnblogs.com/grandyang/p/8445733.html

Last updated

Was this helpful?