LeetCode 323. Number of Connected Components in an Undirected Graph - 彻底掌握并查集(Union Find)系列题16

该博客介绍了如何运用并查集(UnionFind)算法解决图的连通组件计数问题。通过给出的示例代码,展示了如何在Python中实现并查集数据结构,并应用在给定的图数据上,以计算连通组件的数量。题目与LeetCode的200题NumberofIslands的解法相似,是学习并查集的入门实例。
摘要由CSDN通过智能技术生成

You have a graph of n nodes. You are given an integer n and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.

Return the number of connected components in the graph.

Example 1:

Input: n = 5, edges = [[0,1],[1,2],[3,4]]
Output: 2

Example 2:

Input: n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
Output: 1

Constraints:

  • 1 <= n <= 2000
  • 1 <= edges.length <= 5000
  • edges[i].length == 2
  • 0 <= ai <= bi < n
  • ai != bi
  • There are no repeated edges.

一道用于并查集Union Find的入门上手题,解法跟Leetcode200. Number of Islands几乎一模一样,套用Union Find模板几乎不要改动。对每条边的两个顶点进行合并,最后集合个数就是答案。

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(0, n))
        self.size = [1] * n
        self.cnt = n
    
    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    
    def merge(self, x, y):
        px, py = self.find(x), self.find(y)
        if px == py:
            return
        
        if self.size[px] > self.size[py] :
            self.parent[py] = px
            self.size[px] += self.size[py]
        else:
            self.parent[px] = py
            self.size[py] += self.size[px]
                
        self.cnt -= 1
    
class Solution:
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        uf = UnionFind(n)
        
        for e in edges :
            uf.merge(e[0], e[1])
        
        return uf.cnt

可以在刷LeetCode 684. Redundant Connection之前先刷一遍这道题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值