洛谷 P1443 马的遍历

题目概述

    有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步   

解题思路

    使用广搜,注意地图边界和马跳的方向即可。可以采用for代替8个if来减少要码的字。注意栈的读写。

    时间复杂度:O(n*m)

    空间复杂度:O(n*m)

源程序

 

 

const
 d:array[1..2,1..8]of longint=((-2,-2,-1,-1,1,1,2,2),(1,-1,2,-2,2,-2,1,-1));
var
 a:array[1..1002,1..1002]of longint;
 b:array[1..250020,1..2]of longint;
 n,m,x,y,i,j,top,tail:longint;
 s:string;
begin
 readln(n,m,x,y);
 b[1,1]:=x;
 b[1,2]:=y;
 for i:=1 to n do
  for j:=1 to m do
   a[i,j]:=-1;
 a[x,y]:=0;
 top:=0;
 tail:=1;
 while top<tail do
  begin
   inc(top);
   if top>250000 then top:=1;
   for i:=1 to 8 do
    if (b[top,1]+d[1,i]>=1)and(b[top,1]+d[1,i]<=n)
    and(b[top,2]+d[2,i]>=1)and(b[top,2]+d[2,i]<=m)
    and(a[b[top,1]+d[1,i],b[top,2]+d[2,i]]=-1)then
     begin
      inc(tail);
      if tail>250000 then tail:=1;
      b[tail,1]:=b[top,1]+d[1,i];
      b[tail,2]:=b[top,2]+d[2,i];
      a[b[tail,1],b[tail,2]]:=a[b[top,1],b[top,2]]+1;
     end;
  end;
 for i:=1 to n do
  begin
   for j:=1 to m-1 do
    begin
     s:='';
     str(a[i,j],s);
     while length(s)<5 do
      s:=s+' ';
     write(s);
    end;
   writeln(a[i,m]);
  end;
end.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值