Description
求一个图的连通分量
Input
n 顶点数(<=100)
边
Output
连通分量
Sample Input
5
1 2
3 4
2 3
0 0
Sample Output
4
解题思路:用深度优先搜索建立图的邻接矩阵。
程序:
const
maxn=100;
var
g:array[0..maxn,0..maxn]of longint;
a,b:array[0..maxn]of longint;
v:array[0..maxn]of boolean;
n,i,j,t,p,x,y:longint;
procedure dfs(dep,k:longint);
var
i:longint;
begin
v[dep]:=false;
a[dep]:=k;
for i:=1 to n do
if (g[dep,i]=1) and (v[i]) then
begin
v[i]:=false;
dfs(i,k);
end;
end;
begin
readln(n);
repeat
readln(x,y);
g[x,y]:=1;
g[y,x]:=1;
until (x=0) and (y=0);
fillchar(v,sizeof(v),true);
for i:=1 to n do
if v[i] then
begin
inc(p);
dfs(i,p);
end;
for i:=1 to n do
inc(b[a[i]]);
for i:=1 to n-1 do
for j:=i+1 to n do
if b[i]
writeln(b[1]);
end.
版权属于:Chris
原文地址:http://blog.sina.com.cn/s/blog_83ac6af80102v0up.html
转载时必须以链接形式注明原始出处及本声明。