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
A 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.A 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.
A 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 vMOutput
Print the answer.
Sample Input 1 Copy
Copy
5 3 1 2 1 3 4 5Sample Output 1 Copy
Copy
2The 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 0Sample Output 2 Copy
Copy
5
Sample Input 3 Copy
Copy
4 6 1 2 1 3 1 4 2 3 2 4 3 4Sample 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;
}