求无向图的连通分量
求无向图的连通分量 SSL 1759
Description–
求一个图的连通分量
Input–
n 顶点数(<=100)
边
Output–
连通分量
Sample Input–
8
6 3
1 2
2 5
5 4
4 1
8 7
0 0
Sample Output–
4
代码–
方法一
dfs邻接矩阵
#include<cstdio>
#include<iostream>
using namespace std;
int f[110][110],l[110],n,a,b,s,ans;
void dd(int x)
{
l[x]=1;
for (int i=1;i<=n;++i)
if (!l[i] && f[x][i])
{
++s;
dd(i);
}
}
int main()
{
scanf("%d%d%d",&n,&a,&b);
while (a && b)
{
f[a][b]=f[b][a]=1;
scanf("%d%d",&a,&b);
}
for (int i=1;i<=n;i++)
{
s=0;
dd(i);//dfs
ans=max(ans,s);
}
printf("%d",ans+1);
return 0;
}
方法二
dfs邻接表
#include<cstdio>
#include<iostream>
using namespace std;
struct emm
{
int y,next;
}f[10010];
int l[110],h[110],t,ans,s,n,a,b;
void dd(int x)
{
l[x]=1;
for (int i=h[x];i;i=f[i].next)
if (!l[f[i].y])
{
++s;
dd(f[i].y);
}
}
int main()
{
scanf("%d%d%d",&n,&a,&b);
while (a && b)
{
f[++t].y=b; f[t].next=h[a]; h[a]=t;
f[++t].y=a; f[t].next=h[b]; h[b]=t;
scanf("%d%d",&a,&b);
}
for (int i=1;i<=n;i++)
if (!l[i])
{
s=0;
dd(i);//dfs
ans=max(ans,s);
}
printf("%d",ans+1);
return 0;
}