这道题目是一道简单的DFS,只需要用邻接表构出边之后,进行DFS,
一次DFS之后自加1,就可以
贴出代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int N,M;//N represents the number of points,and M stands for the number of edges;
int head[2000];
struct Edge{
int v;
int next;
}e[2000];
int visit[2000];
int idx;
void addedge(int a,int b)
{
idx++;
e[idx].v=b;
e[idx].next=head[a];
head[a]=idx;
}
void DFS(int x)
{
visit[x]=1;
for(int p=head[x];p!=-1;p=e[p].next)
{
int v=e[p].v;
if(!visit[v])
{
DFS(v);
}
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int a,b;
int cn=0;
idx=0;
memset(visit,0,sizeof(visit));
memset(head,-1,sizeof(head));
scanf("%d%d",&N,&M);
for(int i=1;i<=M;i++)
{
scanf("%d%d",&a,&b);
addedge(a,b);
addedge(b,a);
}
for(i=1;i<=N;i++)
{
if(!visit[i])
{
DFS(i);
cn++;
}
}
printf("%d\n",cn);
}
return 0;
}