LeetCode 684. Redundant Connection 解题报告(python)

684. Redundant Connection

  1. Redundant Connection python solution

题目描述

n this problem, a tree is an undirected graph that is connected and has no cycles.

The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, …, N), with one additional 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] with u < v, that represents an undirected edge connecting nodes u and v.

Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v.
在这里插入图片描述

解析

看例子 [1, 2], [1, 3], [2, 3],
1
/
2 - 3
最开始有三个不相邻的集合1, 2, 3.
边 [1,2] 表示1,2在一个集合内
边[1,3] 表示1,3在一个集合内
边 [2,3] 表示 2 , 3在一个集合内。

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        parent=[0]*len(edges)
        def find(x):
            if parent[x]==0:
                return x
            parent[x]=find(parent[x])
            return parent[x]
        
        def union(x,y):
            rootx=find(x)
            rooty=find(y)
            if rootx==rooty:
                return False
            else:
                parent[rootx]=rooty
            return True
        
        for x,y in edges:
            if not union(x-1,y-1):
                return [x,y]
        

Reference

https://leetcode.com/problems/redundant-connection/discuss/123819/Union-Find-with-Explanations-(Java-Python)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值