[LeetCode]Redundant Connection II


LeetCode 685. Redundant Connection II

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:
 / \
v   v

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


  • 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.






统计各顶点的出度/入度 + 拓扑排序 + 并查集


1. 有根树中各顶点的入度均为1。利用拓扑排序,逐层剥离出度为0的顶点,返回剩余边中在edges中排名最后的那一条。

2. 有根树中各顶点入度的最大值为2,则多余的边为不影响树的连通性的那一条。


class Solution(object):
    def findRedundantDirectedConnection(self, edges):
        :type edges: List[List[int]]
        :rtype: List[int]
        def checkConn(ds, dt):
            p = list(range(max(reduce(operator.add, edges)) + 1))
            def find(a):
                while p[a] != a: a = p[a]
                return a
            for s, t in edges:
                if s == ds and t == dt: continue
                ps, pt = find(s), find(t)
                p[pt] = ps
            return find(ds) == find(dt)
        vset = set(reduce(operator.add, edges))
        parents = collections.defaultdict(set)
        inDegree = collections.defaultdict(int)
        outDegree = collections.defaultdict(int)
        for s, t in edges:
            inDegree[t] += 1
            outDegree[s] += 1
        if max(inDegree.values()) > 1:
            for s, t in edges[::-1]:
                if inDegree[t] > 1 and checkConn(s, t): return [s, t]
        degZeros = vset - set(outDegree.keys())
        while degZeros:
            ndegZeros = []
            for t in degZeros:
                deletes = set()
                for s in parents[t]:
                    outDegree[s] -= 1
                    if not outDegree[s]: ndegZeros.append(s)
                del parents[t]
            degZeros = ndegZeros
        for s, t in edges[::-1]:
            if min(outDegree[s], outDegree[t]): return [s, t]



如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码