No323. Number of Connected Components in an Undirected Graph

本文介绍了一种使用并查集解决无向图中连通分量计数问题的方法。通过实例展示了如何初始化每个节点,并逐步合并连通节点,最终计算出连通分量的数量。

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

一、题目描述

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

Example 1:

     0          3
     |          |
     1 --- 2    4

Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], return 2.

Example 2:

     0           4
     |           |
     1 --- 2 --- 3

Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]], return 1.

Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

二、解题思路

使用并查集来解题,关于并查集的介绍,我强烈推荐一篇博客:http://blog.csdn.net/dellaserss/article/details/7724401 ,看完之后醍醐灌顶,以下代码就很好理解了,先把每个点的根设为自己,所以有n个独立不相连的点,然后根据每条边,对每条边的两个点进行寻根,如果一个点的根不是自己,则该点还不是根节点,所以继续寻根,找到一条边的两个顶点的根之后进行比较 ,如果不一样,则将一个的根设定为另一个,这样就将两部分连接起来了。


三、代码实现

public class Solution{
    int countComponents(int n, vector<pair<int, int>>& edges){
        vector<int> root(n);
        int count = n;
        for(int i=0;i<n;i++)
            root[i]=i;
        for(auto p:edges){
            int p1=p.first,p2=p.second;
            while(root[p1]!=p1) p1=root[p1];
            while(root[p2]!=p2) p2=root[p2];
            if(p1!=p2){
                root[p2]=root[p1];
                count--;
            }
        }
        return count;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值