Description
求一个图的连通分量
Input
n 顶点数(<=100)
边
Output
连通分量
Sample Input
5
1 2
3 4
2 3
0 0
Sample Output
4
这题不是很难,主要要在意如果dfs回溯的话,会超时!
这题在dfs的基础上减少了回溯的部分,方可ACE
代码如下:
var n,x,y,i,ans,max,maxn:longint;
a:array[0..101,0..101]of longint;
v:array[0..101]of boolean;
procedure dfs(x:longint);
var i:longint;
begin
for i:=1 to n do
if (a[i,x]=1)and(v[i]=false) then
begin
v[i]:=true;
inc(ans);
dfs(i);
end;
end;
begin
readln(n);
readln(x,y);
while (x<>0)or(y<>0) do
begin
a[x,y]:=1;
a[y,x]:=1;
readln(x,y);
end;
for i:=1 to n do
begin
ans:=0;
dfs(i);
if ans>max then max:=ans;
end;
write(max);
end.