骑士旅行pascal解题程序

来源:互联网 发布:autodesk软件卸载工具 编辑:程序博客网 时间:2024/05/21 15:44

这题我是用广度优先搜索的方法来做的

我先找出下一个能走的点,再把它放进队列里,如果到了目标点,就把tail放进best,tail等于0,最后输出。

做这题的时候,用最大数据时,一直栈溢出,原来是数组不够大,把50*50算成250了,搞得我调试了超久。


const
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
qx,qy,n,m,best:longint;
father:array[1..2500]of longint;
a:array[-1..500,-1..500]of longint;
state:array[1..2500,1..3]of longint;
procedure init;
begin
    readln(n,m);
    read(qx,qy);
    a[1,1]:=1;
end;


procedure bfs;
var
head,tail,wayn,x,y,k:integer;
begin
    father[1]:=0;head:=0;tail:=1;
    state[1,1]:=1;state[1,2]:=1;
    repeat
         inc(head);
         for wayn:=1 to 8 do
         begin
             x:=state[head,1]+dx[wayn];
             y:=state[head,2]+dy[wayn];
             if (x>=1)and(x<=m)and(y>=1)and(y<=n)and(a[x,y]=0) then
             begin
                 inc(tail);father[tail]:=head;
                 state[tail,1]:=x;state[tail,2]:=y;
                 a[x,y]:=1;
                 state[tail,3]:=state[head,3]+1;
                 if (x=qx)and(y=qy) then
                 begin
                     best:=tail;
                     tail:=0;
                     break;
                 end;
             end;
         end;
    until head>=tail;
end;
procedure print;
begin
    if best=0 then writeln('NEVER') else write(state[best,3]);
end;
begin
    init;
    bfs;
    print;
end.

0 0
原创粉丝点击