pascal骑士遍历查错

来源:百度知道 编辑:UC知道 时间:2024/05/19 16:50:46
const
n=8;
dx:array[1..8] of integer=(-2,-2,-1,-1,1,1,2,2);
dy:array[1..8] of integer=(-1,1,-2,2,-2,2,-1,1);
var
step,bx,by,ex,ey:integer;
p:array[1..n,1..n] of integer;
procedure out;
var
i,j:integer;
begin
for i:=1 to 8 do
begin
for j:=1 to 8 do write(p[i,j]);
writeln;
end;
end;
procedure knight(x,y:integer);
var
i,j:integer;
begin
for i:=1 to 8 do
begin
x:=x+dx[i]; y:=y+dy[i];
if (x>0) and (x<=n) and (y>0) and(y<=n)
and (p[x,y]=0)
then begin
step:=step+1;
p[x,y]:=step;
if step<n*n then knight(x,y)
else begin
if (x=ex) and (y=ey) then
begin
out;
halt;

是p[x,y]:=0;这一句的位置不对,x、y已经变回原来的值了,却被赋值0,原来的位置会导致将这搜索的点的step设为0。结果是a数组全是0。还有你记录step只往上加,在回溯时却没有减去。输出时要用write(p[i,j]:3);否则数字会挤在一起。
截取有错的一段改正如下:
if (x>0) and (x<=n) and (y>0) and(y<=n)
and (p[x,y]=0)
then begin
step:=step+1;
p[x,y]:=step;
if step<n*n then knight(x,y)
else begin
if (x=ex) and (y=ey) then
begin
out;
halt;
end;
end;
dec(step); p[x,y]:=0;
end;