ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-07-26 12:06:54  阅读:183  来源: 互联网

标签:int self 查集 father edges 323 无向 find


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)

标签:int,self,查集,father,edges,323,无向,find
来源: https://blog.csdn.net/wq_0708/article/details/119106045

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有