Leetcode 323. 无向图中连通分量的数目

1.题目基本信息

1.1.题目描述

你有一个包含 n 个节点的图。给定一个整数 n 和一个数组 edges ,其中 edges[i] = [ai, bi] 表示图中 ai 和 bi 之间有一条边。

返回 图中已连接分量的数目 。

1.2.题目地址

https://leetcode.cn/problems/number-of-connected-components-in-an-undirected-graph/description/

2.解题方法

2.1.解题思路

并查集/DFS

2.2.解题步骤

并查算法步骤

  • 第一步,构建维护变量。使用rootDict记录各个节点归属的集合的根节点。

  • 第二步,构建并查集中用于寻找到节点x所在集合的根节点的函数

  • 第三步,遍历所有的边,根据并查集求联通分量个数

DFS算法步骤

  • 第一步,使用邻接表构建无向图

  • 第二步,构建维护变量。使用visited记录已经遍历过的点

  • 第三步,通过DFS计算连通分量的个数

3.解题代码

并查集版本代码

class Solution:
    # 并查算法
    def countComponents(self, n: int, edges: List[List[int]]) -> int:
        # 记录几点i所在集合的根节点,下面的集合表示root相同的节点构成的集合
        self.rootDict={i:i for i in range(n)}
        # 找到节点x所在集合的根节点
        def findRoot(x):
            # 根节点为本身的就是根节点
            root=self.rootDict[x]
            while root!=self.rootDict[root]:
                root=self.rootDict[root]
            return root
        cnt=n
        for edge in edges:
            root1=findRoot(edge[0])
            root2=findRoot(edge[1])
            if root1!=root2:
                # 说明需要两个的点不在同一集合上
                cnt-=1
                # 更新后面节点的根节点
                self.rootDict[root2]=root1
        return cnt

DFS版本代码

class Solution:
    # DFS
    def countComponents1(self, n: int, edges: List[List[int]]) -> int:
        # 构建图
        graph={i:[] for i in range(n)}
        for edge in edges:
            graph[edge[0]].append(edge[1])
            graph[edge[1]].append(edge[0])
        def dfs(node):
            self.visited.add(node)
            for subNode in graph[node]:
                if subNode not in self.visited:
                    dfs(subNode)
        # 已经遍历过的点
        self.visited=set()
        # 连通分量的个数
        cnt=0
        for node in list(graph.keys()):
            if node not in self.visited:
                dfs(node)
                cnt+=1
        return cnt

4.执行结果

posted @ 2025-05-28 09:16  Geek0070  阅读(62)  评论(0)    收藏  举报