[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:
  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.

题目大意:

输入一组边edges表示一棵有根树。

有根树恰好多余一条边,求这条多余的边。

若答案不唯一,则返回在edges中排名最后的那条边。

解题思路:

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

当有根树多余一条边时,分为两种情况:

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

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

Python代码:

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:
            parents[t].add(s)
            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)
                    deletes.add(s)
                del parents[t]
            degZeros = ndegZeros
        for s, t in edges[::-1]:
            if min(outDegree[s], outDegree[t]): return [s, t]

 

本文链接:http://bookshadow.com/weblog/2017/09/26/leetcode-redundant-connection-ii/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

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

Pingbacks已关闭。

暂无评论

张贴您的评论