【C语言】【dfs】无向连通子图个数

C - Count Connected Components

Problem Statement

You are given a simple undirected graph with N vertices numbered 1to N and M edges numbered 1 to M. Edge i connects vertex ui​ and vertex vi​.
Find the number of connected components in this graph.

Notes

simple undirected graph is a graph that is simple and has undirected edges.
A graph is simple if and only if it has no self-loop or multi-edge.

subgraph of a graph is a graph formed from some of the vertices and edges of that graph.
A graph is connected if and only if one can travel between every pair of vertices via edges.
connected component is a connected subgraph that is not part of any larger connected subgraph.

Constraints

  • 1≤N≤100
  • 0≤M≤2N(N−1)​
  • 1≤ui​,vi​≤N
  • The given graph is simple.
  • All values in the input are integers.

Input

The input is given from Standard Input in the following format:

N M
u1​ v1​
u2​ v2​
⋮⋮
uM​ vM​

Output

Print the answer.


Sample Input 1 Copy

Copy

5 3
1 2
1 3
4 5

Sample Output 1 Copy

Copy

2

The given graph contains the following two connected components:

  • a subgraph formed from vertices 11, 22, 33, and edges 11, 22;
  • a subgraph formed from vertices 44, 55, and edge 33.


Sample Input 2 Copy

Copy

5 0

Sample Output 2 Copy

Copy

5

Sample Input 3 Copy

Copy

4 6
1 2
1 3
1 4
2 3
2 4
3 4

Sample Output 3 Copy

Copy

1

思路

首先,得到图的邻接矩阵

然后,以每个点为起点,分别进行深搜,详细可以看代码注释,非常详细

代码实现

#include<bits/stdc++.h>
using namespace std;
int n,m,a[105][105],v[105];
void dfs(int x)
{
    v[x]=1;//标记该点已遍历
    for(int i=1;i<=n;i++)//遍历所有点,查看当前点与所有点的关系
    {
        //v[i]==0正好可以排除已经遍历过的点进行深搜(尤其是上面两行标记的自己v[x]=1),防止陷入死循环
        if(v[i]==0&&a[i][x]==1)//当前的与遍历到的点连通
        {
            dfs(i);
        }
    }
}
int main()
{
    scanf("%d %d",&n,&m);
//    int a[5000][2];
    int x,y;
    for(int i=0;i<m;i++)
    {
        scanf("%d %d",&x,&y);
        a[x][y]=1;//获得邻接矩阵
        a[y][x]=1;
    }
    int count=0;
    for(int i=1;i<=n;i++)//以每个点为起点分别遍历
    {
        //如果该点之前遍历过了,证明该点与它之前的点连通,那肯定在深搜的部分遍历过了
        if(v[i]==0)//该点之前没有遍历过
        {
            dfs(i);//从该点开始深搜
            count++;//深搜到底,子图加一
        }
    }
    printf("%d",count);
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值