求连通分量
Time Limit:1000MS Memory Limit:65536K
Total Submit:233 Accepted:132
Description
求一个图的连通分量
Input
n 顶点数(<=100)边
Output
连通分量
Sample Input
5
1 2
3 4
2 3
0 0
Sample Output
4
首先解释一下样例输入:
5 //顶点的数量
1 2 //顶点1和顶点2相连
3 4 //顶点3和顶点4相连
2 3 //顶点2和顶点3相连
0 0 //两个零表示结束
输出的就是最多有几个点是连在一起的
这题在dfs的基础上减少了回溯的那一部分,输入稍微麻烦一点
var
i,n,x,y,ans,max:longint;
b:array[0..101,0..101]of boolean;
a:array[0..101]of boolean;
procedure dfs(k:longint);
var i:longint;
begin
for i:=1 to n do
if (b[i,k])and(a[i]=false) then
begin
a[i]:=true;
inc(ans);
dfs(i);
end;
end;
begin
readln(n);
readln(x,y);
while (x<>0)or(y<>0) do
begin
b[x,y]:=true;
b[y,x]:=true;
readln(x,y);
end;
for i:=1 to n do
begin
ans:=0;
dfs(i);
if ans>max then max:=ans;
end;
writeln(max);
end.