骑士旅行 1456

  • 骑士旅行

    Time Limit:1000MS  Memory Limit:65536K Total Submit:249 Accepted:91

    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

    5 3
    1 2
    

    Sample Output

    3

    Source

    elba

    纯属广搜,注意方向
  • 
    
  • const
      maxn=50;
      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
      i,j,k,n,m,qx,qy,max,best:longint;
      a,state:array[-maxn*maxn..maxn*maxn,-maxn*maxn..maxn*maxn]of longint;
      father:array[-maxn*maxn..maxn*maxn]of longint;
    
    procedure init;
    var
      i,j,k:longint;
    begin
      readln(n,m);
      readln(qx,qy);
      a[1,1]:=1;
    end;
    
    procedure print;
    var
      i,j:longint;
    begin
      if best=0 then writeln('NEVER')
      else writeln(state[best,3]);
    end;
    
    procedure dfs;
    var
      i,j,head,tail,x,y:longint;
    begin
      father[1]:=0;
      head:=0;
      tail:=1;
      state[1,1]:=1; state[1,2]:=1; state[1,3]:=0;
      repeat
        inc(head);
        for i:=1 to 8 do
          begin
            x:=state[head,1]+dx[i];
            y:=state[head,2]+dy[i];
            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;
    
    
    begin
      init;
      dfs;
      print;
    end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值