洛谷 P1443 马的遍历

10 篇文章 0 订阅

洛谷 P1443 马的遍历


题目

题目描述

有一个n*m的棋盘(1

题目


题解

BFS+手动左对齐(Pascal没有左对齐)


代码(Pascal)

const flag:array[1..8,0..1]of longint=((2,1),(1,2),(-1,2),(2,-1),(-2,-1),(-1,-2),(-2,1),(1,-2));
var n,m,head,tail:longint;
    q:array[0..160005]of record
                           x,y:longint;
                          end;
    map:array[0..405,0..405]of longint;
    vis:array[0..405,0..405]of boolean;
 procedure init;
  begin
    readln(n,m,q[1].x,q[1].y);
   end;
 function check(x,y:longint):boolean;
  begin
    if (x<1)or(y<1)or(x>n)or(y>m) then exit(false);
    if vis[x,y]=true then exit(false);
    exit(true);
   end;
 procedure find(x,y:longint);
  begin
    inc(tail);vis[x,y]:=true;
    q[tail].x:=x;q[tail].y:=y;
    map[x,y]:=map[q[head].x,q[head].y]+1;
   end;
 procedure print(x:longint);
  var i,t,y:longint;
   begin
     t:=0;y:=x;
     if x<0 then begin
                   x:=abs(x);
                   inc(t);
                  end;
     if (x<=9) then inc(t) else
     if (x<=99) then t:=t+2 else
     if (x<=999) then t:=t+3 else
     if (x<=9999) then t:=t+4;
     write(y);
     for i:=1 to 5-t do
      write(' ');
    end;
 procedure main;
  var i,j,x,y:longint;
   begin
     fillchar(vis,sizeof(vis),0);
     head:=0;tail:=1;
     for i:=1 to n do
      for j:=1 to m do
       map[i,j]:=-1;
     map[q[1].x,q[1].y]:=0;
     vis[q[1].x,q[1].y]:=true;
     while head<tail do
      begin
        inc(head);
        x:=q[head].x;y:=q[head].y;
        for i:=1 to 8 do
         if check(x+flag[i,0],y+flag[i,1]) then find(x+flag[i,0],y+flag[i,1]);
       end;
     for i:=1 to n do
      begin
        for j:=1 to m do print(map[i,j]);
        writeln;
       end;
     end;
 begin
   init;
   main;
  end.
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值