684. 冗余连接(并查集)(傻瓜教程)(python)(LC)

684. 冗余连接

在本问题中, 树指的是一个连通且无环的无向图。

输入一个图,该图由一个有着N个节点 (节点值不重复1, 2, …, N) 的树及一条附加的边构成。附加的边的两个顶点包含在1到N中间,这条附加的边不属于树中已存在的边。

结果图是一个以边组成的二维数组。每一个边的元素是一对[u, v] ,满足 u < v,表示连接顶点u 和v的无向图的边。

返回一条可以删去的边,使得结果图是一个有着N个节点的树。如果有多个答案,则返回二维数组中最后出现的边。答案边 [u, v] 应满足相同的格式 u < v。


示例 1:

输入: [[1,2], [1,3], [2,3]]
输出: [2,3]
解释: 给定的无向图为:
  1
 / \
2 - 3

示例 2:

输入: [[1,2], [2,3], [3,4], [1,4], [1,5]]
输出: [1,4]
解释: 给定的无向图为:
5 - 1 - 2
    |   |
    4 - 3

解题

核心思想就是解决对标题“冗余连接”的判断

在这里我们直接调用并查集的内置函数来解决(以下是并查集的定义)

class UF:
    def __init__(self, M):
        self.parent = {
    
    }
        self.cnt = 0
        # 初始化 parent,size 和 cnt
        for i in range(M):
            self.parent[i] = i
            self.cnt += 1
            
    def find(self, x):
    	root = x
        while self.father[root] != root:
            root = self.father[root]   
        # 路径压缩
        while x != root:
            original_father = self.father[x]
            self.father[x] = root
            x = original_father    
        return root

    def union(self, p, q):
        if self.connected(p, q): return
        leader_p = self.find(p)
        leader_q = self.find(q)
        self.parent[leader_p] = leader_q
        self.cnt -= 1
        
    def connected(self, p, q):
        return self.find(p) == self.find(q)

代码

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        uf = UF(1001)  # 1.初始化
        for p, q in edges:  
            if uf.connected(p, q): return [p, q]  # 2.判断
            uf.union(p, q)  # 3.添加连接

猜你喜欢

转载自blog.csdn.net/qq_51174011/article/details/112662726