三种方法求图中连通分量的个数(BFS、DFS、并查集)

2023-05-16

1. 连通分量是什么

无向图G的极大连通子图称为G的连通分量( Connected Component)。任何连通图的连通分量只有一个,即是其自身,非连通的无向图有多个连通分量。

2. 案例

2.1.图极其数据结构初始化

在这里插入图片描述

2.2.求连通分量的方法

从每个顶点出发,判断是否有连通分量
BFS[BFS](https://blog.csdn.net/qq_44423388/article/details/127591933?spm=1001.2014.3001.5501)
DFS[DFS](https://blog.csdn.net/qq_44423388/article/details/127583096?spm=1001.2014.3001.5501)
并查集(本篇主讲,实现步骤见下)

在这里插入图片描述
在这里插入图片描述

2.3 具体实现

/*
测试用例:
1 2
1 4
2 4
*/


#include <vector>
#include <iostream>
#include <queue>
#include <unordered_map>

using namespace std;

/*
如果节点是相互连通的(从一个节点可以到达另一个节点),那么他们在同一棵树里,或者说在同一个集合里,或者说他们的祖先是相同的。
*/
//并查集的数据结构
class UnionFind {

private:
    // 记录每一个节点的父节点father<当前节点下标,父节点下标>
    unordered_map<int, int> father;
    // 记录集合数量
    int num_of_sets = 0;

public:

    //找节点x的父节点
    int find(int x) 
    {
        int root = x;

        while (father[root] != -1) 
        {
            root = father[root];
        }
        //优化的点:如果我们树很深,那么每次查询的效率都会非常低。这一步把树的深度固定为二。
        while (x != root) 
        {
            int original_father = father[x];
            father[x] = root;
            x = original_father;
        }

        return root;
    }

    bool is_connected(int x, int y) 
    {
        return find(x) == find(y);
    }

    //将连通的两个节点合并为同一个祖先,同时并查集的数目--
    void merge(int x, int y) 
    {
        int root_x = find(x);
        int root_y = find(y);

        if (root_x != root_y)
        {
            father[root_y] = root_x;
            num_of_sets--;
        }
    }
    //将新节点添加到并查集中
    void add(int x) 
    {
        if (!father.count(x))
        {
            father[x] = -1;
            num_of_sets++;
        }
    }
    //返回并查集个数
    int get_num_of_sets()
    {
        auto it = father.begin();
        while (it != father.end())
        {
            cout << it->first<<" ->"<<it->second << endl;
            it++;
        }
        
        return num_of_sets;
    }
};

class Connectedcomponent:protected UnionFind
{
private:
    int vertice = 0;//顶点数
    int edge = 0;//边数
    vector<vector<int>> e;
    //因为dfs和bfs都会对其进行改变,所有设置两个book
    vector<bool> book;//判断顶点j是否扩展过
    vector<bool> book1;//判断顶点j是否扩展过
    queue<int> qu;

    //DFS求连通分量个数
    void DFS_Alg(int current, int sum)//current当前所在的节点编号
    {
        sum++;
        if (sum == vertice)//所有的节点均已被访问
        {
            cout << current << endl;
            return;
        }
        else
        {
            cout << current << " ->";
        }
        for (int k = 1; k <= vertice; k++)
        {
            if (e[current][k] != 0 && book[k] == 0)
            {
                book[k] = 1;
                DFS_Alg(k, sum);
            }
        }
    }
    
public:
    Connectedcomponent(int x, int y) :vertice(x), edge(y)
    {
        //图的初始化从下标1开始
        e.resize(vertice + 1);//初始化二维数组的行
        for (int i = 0; i <= vertice; i++)
        {
            e[i].resize(vertice + 1,0);//初始化二维数组的列
        }
        
        book.resize(vertice + 1);
        book1.resize(vertice + 1);
    }
    //图的初始化
    void Init_tu()
    {
        for (int i = 0; i <= vertice; i++)
        {
            for (int j = 0; j <= vertice; j++)
            {
                if (i == 0 || j == 0)
                {
                    e[i][j] = 0;
                }
                if (i == j)
                {
                    e[i][j] = 0;
                }
                else
                {
                    e[i][j] = INT_MAX;
                }
            }
        }
    }
    //读入图的边,并且根据边的信息初始化数组dis,数组book
    void GetEdgeInfo()
    {
        cout << "输入边的信息(节点1,节点2):" << endl;
        int e1 = 0, e2 = 0, weigth = 0;
        for (int i = 1; i <= edge; i++)//无向图
        {
            cin >> e1 >> e2;
            e[e1][e2] = 1;
            e[e2][e1] = 1;
        }        
    }

    //打印
    void Print()
    {
        for (int i = 1; i <= vertice; i++)
        {
            for (int j = 1; j <= vertice; j++)
            {
                cout << e[i][j] << "    ";
            }
            cout << endl;
        }
        cout << endl;
    }
    
    int DFS_Num()
    {
        int num = 0;
        for (int i = 1; i <= vertice; i++)
        {
            if (book[i] == false)
            {
                DFS_Alg(i,0);
                cout <<"end" <<endl;
                num++;
            }               
        }

        return num;
    }
    //BFS求连通分量个数
    int BFS_Num()
    {     
        int num = 0;
        for (int i = 1; i <= vertice; i++)//遍历每个节点,查看是否从该节点出发是否有连通分量
        {
            if (book1[i] == false)
            {
                qu.push(i);
                while (!qu.empty())
                {
                    int v = qu.front();
                    qu.pop();
                    book1[v] = true;
                    cout << v << "->";
                    for (int i = 1; i <= vertice; i++)//循坏找节点v的相邻节点
                    {
                        if (e[v][i] != 0 && book1[i] == false)
                        {
                            qu.push(i);
                            book1[i] = true;
                        }
                    }
                }
                num++;
            }            
            
            cout << "end" << endl;
        }
        return num;       

    }
    //并查集求连通分量的个数
    /*
    每个节点会记录它的父节点。
    */
    int UnionFindSet()
    {
        UnionFind uf;
        for (int i = 1; i <= vertice; i++)
        {
            uf.add(i);
            for (int j = 1; j < i; j++)
            {
                if (e[i][j] == 1)
                {
                    uf.merge(i, j);
                }
            }
        }

        return uf.get_num_of_sets();
    }
};

int main()
{
    int num1 = 0, num2 = 0,num3 = 0;
    Connectedcomponent Conn(5, 3);
    Conn.GetEdgeInfo();

    cout << "初始信息:" << endl;
    Conn.Print();
    
    cout << "DFS:::" << endl;
    num1 = Conn.DFS_Num();
    cout << "BFS:::" << endl;
    num2 = Conn.BFS_Num();


    cout << "Union Find Set:::" << endl;
    num3 = Conn.UnionFindSet();
    cout << num1 << "  " << num2 <<"   "<<num3<< endl;

    return 0;
}

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

三种方法求图中连通分量的个数(BFS、DFS、并查集) 的相关文章

  • 从零开始系列(二):数据库基础篇

    从零开始系列 xff08 二 xff09 xff1a 数据库基础篇 相关系列文章推荐 xff1a 从零开始系列 xff08 一 xff09 xff1a 在github上搭建自己的博客 从零开始系列 xff08 三 xff09 xff1a W
  • 从零开始系列(三):Windows10安装Linux子系统(WSL教程)

    从零开始系列 xff08 三 xff09 xff1a Windows10安装Linux子系统 xff08 WSL教程 xff09 相关系列文章推荐 xff1a 从零开始系列 xff08 一 xff09 xff1a 在github上搭建自己的
  • 从零开始系列(四):一文看懂arm架构和x86架构有什么区别

    从零开始系列 xff08 四 xff09 xff1a 一文看懂arm架构和x86架构有什么区别 相关系列文章推荐 xff1a 从零开始系列 xff08 一 xff09 xff1a 在github上搭建自己的博客 从零开始系列 xff08 二
  • NVIDIA显卡及架构介绍

    版权申明 未经博主同意 xff0c 谢绝转载 xff01 xff08 请尊重原创 xff0c 博主保留追究权 xff09 xff1b 本博客的内容来自于 xff1a NVIDIA显卡及架构介绍 xff1b 学习 合作与交流联系q384660
  • 脉冲神经网络资料汇总

    往期文章推荐 xff1a 损失函数与代价函数 神经网络从入门到精通 脉冲神经网络综述笔记 版权申明 未经博主同意 xff0c 谢绝转载 xff01 xff08 请尊重原创 xff0c 博主保留追究权 xff09 xff1b 本博客的内容来自
  • 什么是NAS

    一 NAS是什么 简单的说就是连接在网络上 xff0c 让大家可以透过网络 xff08 内网 xff0c 外网 xff09 来进行储存和读取资料的设备 通俗点说 xff0c 就是有一台很小很小的台式主机 xff0c 里面只装了很多颗的磁盘
  • numba安装与使用

    一 numba是什么 Numba是一个针对Python的开源JIT编译器 xff0c 由Anaconda公司主导开发 xff0c 可以对Python原生代码进行CPU和GPU加速 Numba对NumPy数组和函数非常友好 解释器可以参考第四
  • 目标检测中算法评价指标FPS

    一 FPS 每秒传输帧数 Frames Per Second 是什么 FPS就是目标网络每秒可以处理 xff08 检测 xff09 多少帧 多少张图片 FPS简单来理解就是图像的刷新频率 xff0c 也就是每秒多少帧 假设目标检测网络处理1
  • pytorch版本对计算能力的要求

    一 pytorch对计算能力要求 首先查看pytorch是否可用cuda完整流程应该是先查看是否在当前环境下的python In span class token punctuation span span class token numb
  • 在VS2013中配置boost_1_58_0过程和遇到的的问题

    Boost是为C 43 43 语言标准库提供扩展的一些C 43 43 程序库的总称 Boost库是一个可移植 提供源代码的C 43 43 库 xff0c 作为标准库的后备 xff0c 是C 43 43 标准化进程的开发引擎之一 xff0c
  • C语言学习专栏(1):易忘点

    C语言学习专栏系列 xff1a 版权申明 未经博主同意 xff0c 谢绝转载 xff01 xff08 请尊重原创 xff0c 博主保留追究权 xff09 xff1b 本博客的内容来自于 xff1a C语言学习专栏 xff08 1 xff09
  • git如何配置模板文件

    git如何创建模板文件 创建xxx template文件 xff0c 其内容为团队制定的Git提交注释规范 xff0c 如 xff1a Desgraption Date Author 通过git config命令配置commit templ
  • iOS很坑的error:

    iOS错误如下 error using bridging headers with module interfaces is unsupported 仔细看好错误类型 xff0c 是关于swift混合编译问题 解决办法 完美解决 xff0c
  • 使用Hexo搭建个人博客,绑定GitHub以及个人域名

    文章目录 前言安装Git安装Nodejs安装Hexo创建一个根目录安装Hexo验证安装是否成功初始化网址安装网址依赖开启本地服务 托管到Git配置git的SSH在github上配置秘钥 托管到GitHub配置仓库地址hexo安装部署的命令验
  • ubuntu定时任务的设置

    ubuntu 定时执行任务需要进行如下操作 xff1a span class token comment 使用 crontab 添加定时任务 span span class token comment 1 打开定时任务 span span
  • linux静态库、linux动态库制作、使用,动态库报错:error while loading shared libraries: libxxx.so: cannot open shared o

    接上一篇 xff1a linux C C 43 43 程序编译 gcc编译器基础使用 编译阶段 编译优化 命令大全 g 43 43 适用 本次来分享linux下C C 43 43 程序的静态库和动态库的制作和使用 xff0c 不废话 xff
  • SpringBoot热部署四步完成(idea2021.1)

    1 在pom xml文件中设置 xff08 两小步 xff09 span class token number 1 1 span xff1a 在 span class token generics span class token punc
  • spring boot中.yml配置日志文件格式正确运行出错(logging level)

    yml文件配置logging出错 格式如下 logging span class token operator span level span class token operator span com span class token p
  • 基本类型的字面值及其类型转换

    基本类型的字面值及其类型转换 一 基本类型的字面值二 类型转换 一 基本类型的字面值 1 整数字面值是int类型 2 byte xff0c short xff0c char三种比int小的整数可以用范围内的值直接赋值 3 浮点数的字面值是d
  • 使用idea创建servlet程序(idea:2021.2)

    使用idea创建servlet程序 1 Feil gt New gt Project 2 创建一个java项目 创建好之后项目结构如下图 右键项目点击Add Frameworks Support 勾选Web Application如下图 x

随机推荐