SSL 1455
第一次BFS感受
特爽,超级爽,比DFS快!就是难打点。
题目描述
如下图12×12方格图,找出一条自入口(2,9)到出口(11,8)的最短路径。
解析
在代码里
代码
const
dx:array[1..4]of longint=(1,-1,0,0);
dy:array[1..4]of longint=(0,0,1,-1);
var
n,b1,b2,e1,e2,sum,l:longint;
a:array[1..100,1..100]of longint;
f:array[1..10000]of longint;
s:array[1..100,1..2]of longint;
procedure init;
var
i,j:longint;
begin
readln(n);
readln(b1,b2,e1,e2);
for i:=1 to n do
begin
for j:=1 to n do
read(a[i,j]);
readln;
end;
end;
function ping(x,y:longint):boolean;//判断重复
var
i:longint;
begin
if a[x,y]=1 then exit(false);
exit(true);
end;
procedure print(n:longint);
begin
if n=0 then begin l:=sum;exit; end;
inc(sum);
print(f[n]);//逆向跟踪父节点,打出坐标
dec(l);
if l<>0 then write('(',s[n,1],',',s[n,2],')->')
else write('(',s[n,1],',',s[n,2],')');
end;
procedure bfs;
var
i,h,t:longint;
begin
h:=0;t:=1;s[1,1]:=b1;s[1,2]:=b2;
repeat
inc(h);//头指针往后(层次往下)
for i:=1 to 4 do//因为老鼠能走四个方向,所以设定好移动数组(dx,dy)后很方便用来确定以及在这一层逐个搜索节点
if ping(s[h,1]+dx[i],s[h,2]+dy[i]) then
begin
inc(t);//尾指针往后(在该层次搜索下个节点)
f[t]:=h;//记录父节点
s[t,1]:=s[h,1]+dx[i];
s[t,2]:=s[h,2]+dy[i];
a[s[t,1],s[t,2]]:=1;//重复标记(走过的标记,这样不会死循环)
if (s[t,1]=e1)and(s[t,2]=e2) then//判断是否到终点
begin
print(t);
exit;
end;
end;
until h=t;
end;
begin
init;
bfs;
writeln;
writeln(sum);
end.
人生第一道的广搜题啊哈哈哈哈哈哈