Leetcode 684. Redundant Connection (python)

本文介绍了LeetCode第684题——冗余连接的解题思路,包括使用深度优先搜索(DFS)和并查集(UnionFind)两种方法,并提供了Python和C++的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Leetcode 684. Redundant Connection

题目

在这里插入图片描述

解法1:dfs

一次构建图,返回第一组成环的边。

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        def dfs(source,target):
            if source in seen:
                return 
            seen.add(source)
            if source == target:
                return True
            flag = False
            for nei in graph[source]:
                flag = flag or dfs(nei,target)
            return flag
        
        graph = collections.defaultdict(set)
        
        for u,v in edges:
            seen = set()
            if u in graph and v in graph and dfs(u,v):
                return u,v
            graph[u].add(v)
            graph[v].add(u)

解法2:unionfind

python版本:

class Solution:
    def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:
        def find(p):
            while p != _id[p]:
                p = _id[p]
            return p
        def union(p,q):
            _id[find(p)] = find(q)
        def isconnected(p,q):
            return find(q) == find(p)
        n = len(edges)
        _id = [0]*(n+1)
        for i in range(n+1):
            _id[i] = i
        for edge in edges:
            u = edge[0]
            v = edge[1]
            if isconnected(u,v):
                return edge
            union(u,v)
        return [-1,-1]

c++版本:

class UF{
    vector<int> id;
public:
    UF(int n):id(n){
        for (int i=0;i<n;i++){
            id[i] = i;
        }
    }
    
    int find(int p){
        while (p != id[p]){
            p = id[p];
        }
        return p;
    }
    
    void union_node(int p, int q){
        id[find(p)] = find(q);
    }
    
    bool isConnected(int p,int q){
        return find(p) == find(q);
    }
};
class Solution {
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        int n = edges.size();
        UF uf(n+1);
        for (auto e:edges){
            int u=e[0], v=e[1];
            if (uf.isConnected(u,v)){
                return e;
            }
            uf.union_node(u,v);
        }
        return {-1,-1};
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值