leetcode-685-冗余连接②

题目描述:

leetcode-685-冗余连接②

 

 leetcode-685-冗余连接②

 

 参考后提交:并查集:

leetcode-685-冗余连接②

class Solution:
    def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:
        def find(f,x):
            f.setdefault(x,x)
            if f[x] != x:
                f[x] = find(f,f[x])
            return f[x]
        def cycle(graph):
            f = {}
            for x,y in graph:
                if find(f,x) == find(f,y):
                    return True
                else:
                    f[find(f,y)] = find(f,x)
        indegree = {i:0 for i in range(1,len(edges)+1)}
        tmp = 0
        for i,j in edges:
            indegree[j] += 1
            if indegree[j] == 2:
                tmp = j
                break
        if tmp == 0:
            f = {}
            for x,y in edges:
                if find(f,x) == find(f,y):
                    return [x,y]
                else:
                    f[find(f,y)] = find(f,x)
        else:
            for x,y in edges[::-1]:
                if y == tmp:
                    if not cycle(edges[:edges.index([x,y])]+edges[edges.index([x,y])+1:]) :
                        return [x,y]
        

 

上一篇:Coloring Edges CodeForces - 1217D


下一篇:洛谷 P2756 飞行员配对方案问题 (二分图/网络流,最佳匹配方案)