Leetcode #323:无向图中连通分量数(并查集)

Leetcode #323:无向图中连通分量数(并查集)

题目

题干

该问题 无向图中连通分量数,看题面:
无向图中连通分量数

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.

给定编号从 0 到 n-1 的 n 个节点和一个无向边列表(每条边都是一对节点),请编写一个函数来计算无向图中连通分量的数目。

示例

示例 1:
输入: n = 5 和 edges = [[0, 1], [1, 2], [3, 4]]
输出:2
解释:

 0        3
 |        |
 1 --- 2  4

示例 2:
输入: n = 5 和 edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
输出:1
解释:

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

注意:你可以假设在 edges 中不会出现重复的边。而且由于所以的边都是无向边,[0, 1] 与 [1, 0] 相同,所以它们不会同时在 edges 中出现。

题解

思路:这个题目可以转化为用并查集求一共有多少个老大的问题。

C++

class Solution {
public:
    //找每一个顶点的老大
    int find_father(vector<int> &f, int i){
        while(i!=f[i]){
            i=f[i];
        } 
        return i;
    }
 
    int countComponents(int n, vector<vector<int>>& edges) {
        vector<int>f(n);
        //将每一个顶点单独分成一组
        for(int i=0; i<n; ++i){
            f[i]=i;
        }
        //进行同一组的顶点的合并
        for(auto x:edges){
            int p=find_father(f, x[0]);
            int q=find_father(f, x[1]);
            if(p==q) continue;
            else f[p]=q;
        }        
        //找一共有多少个不同的老大
        unordered_set<int>s;
        for(int i=0; i<f.size(); ++i){
            s.insert(find_father(f, i));
        }
        return s.size();
    }
};

Python

class Solution:
    def __init__(self, n: int, edges: list):
        self.n = n
        self.edges = edges

    def find_father(self, f: list, i: int):
        while i != f[i]:
            i = f[i]
        return i

    def count_components(self):
        # 将每一个顶点单独分成一组
        f = list(range(self.n))
        # 进行同一组的顶点的合并
        for x in self.edges:
            p = self.find_father(f, x[0])
            q = self.find_father(f, x[1])
            if p==q:
                continue
            else:
                f[p] = q
        # 找一共有多少个不同的老大
        s = set()
        for i in range(len(f)):
            s.add(self.find_father(f, i))
        return len(s)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值