算法:搜索
很简单的一道搜索题,唯一需要注意的是横竖是颠倒的,这一点需要特别注意,第一次做的时候错就错在这了。。
program graph;
const
maxn=1000;
maxzt=1000000;
dx:array [1..4] of -1..1=(0,-1,0,1);
dy:array [1..4] of -1..1=(-1,0,1,0);
type
atp=record
x,y,dep:longint;
end;
var
n,head,tail,tot:longint;
ans:array [0..maxzt] of longint;
a:array [0..maxn,0..maxn] of char;
que:array [0..maxzt] of atp;
procedure init;
var
i,j:longint;
begin
readln(n);
for i:=1 to n do
begin
for j:=1 to n do read(a[i,j]);
readln;
end;
end;
procedure bfs(x,y:longint);
var
i,tx,ty:longint;
begin
head:=0;
tail:=1;
que[1].x:=x;
que[1].y:=y;
que[1].dep:=1;
a[x,y]:='0';
while head<tail do
begin
inc(head);
for i:=1 to 4 do
begin
tx:=que[head].x+dx[i];
ty:=que[head].y+dy[i];
if (tx>0) and (tx<=n) and (ty>0) and (ty<=n) and (a[tx,ty]='1') then
begin
a[tx,ty]:='0';
inc(tail);
que[tail].x:=tx;
que[tail].y:=ty;
que[tail].dep:=que[head].dep+1;
end;
end;
end;
inc(tot);
ans[tot]:=que[tail].dep;
end;
procedure qsort(l,r:longint);
var
i,j,m,t:longint;
begin
i:=l;
j:=r;
m:=ans[(l+r) shr 1];
repeat
while ans[i]<m do inc(i);
while ans[j]>m do dec(j);
if i<=j then
begin
t:=ans[i];
ans[i]:=ans[j];
ans[j]:=t;
inc(i);
dec(j);
end;
until i>j;
if i<r then qsort(i,r);
if l<j then qsort(l,j);
end;
procedure main;
var
i,j:longint;
begin
for j:=1 to n do
begin
for i:=1 to n do
if a[i,j]='1' then bfs(i,j);
end;
qsort(1,tot);
end;
procedure print;
var
i:longint;
begin
writeln(tot);
for i:=1 to tot do writeln(ans[i]);
end;
begin
assign(input,'graph.in'); reset(input);
assign(output,'graph.out'); rewrite(output);
init;
main;
print;
close(input); close(output);
end.
本文探讨了一道关于搜索算法的题目,强调了题目中横竖颠倒这一关键点,通过详细步骤阐述了如何正确解决该问题,并分享了优化思路。
1025

被折叠的 条评论
为什么被折叠?



