Description
在一个n m 格子的棋盘上,有一只国际象棋的骑士在棋盘的左下角 (1;1)(如图1),骑士只能根据象棋的规则进行移动,要么横向跳动一格纵向跳动两格,要么纵向跳动一格横向跳动两格。 例如, n=4,m=3 时,若骑士在格子(2;1) (如图2), 则骑士只能移入下面格子:(1;3),(3;3) 或 (4;2);对于给定正整数n,m,I,j值 (m,n<=50,I<=n,j<=m) ,你要测算出从初始位置(1;1) 到格子(i;j)最少需要多少次移动。如果不可能到达目标位置,则输出”NEVER”。
Input
输入文件的第一行为两个整数n与m,第二行为两个整数i与j。
Output
输出文件仅包含一个整数为初始位置(1;1) 到格子(i;j)最少移动次数。
Sample Input
Sample Output
先定义常量数组,说明可能行走的路径,然后用队列的思想,最后按要求输出’NEVER’或者最佳答案。
程序:
const
maxn=50;
dx:array[1..8] of integer=(2, 1,-1,-2,-2,-1, 1, 2);
dy:array[1..8] of integer=(1, 2, 2, 1,-1,-2,-2,-1);
var
a:array[-1..maxn+2,-1..maxn+2] of integer;
father:array[1..maxn*maxn] of integer;
state:array[1..maxn*maxn,1..3] of integer;
n,m,qx,qy,best:integer;
procedure init;
begin
fillchar(a,sizeof(a),0);
fillchar(state,sizeof(state),0);
fillchar(father,sizeof(father),0);
readln(n,m);
readln(qx,qy);
a[1,1]:=1;
best:=0;
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;state[1,3]:=0;
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
tail:=tail+1;
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;
end;
end;
end;
until head>=tail;
end;
procedure print;
begin
if best=0 then writeln('NEVER')
else writeln(state[best,3]);
end;
begin
init;
bfs;
print;
end.