• 马的遍历


    题目描述

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

    输入输出格式

    输入格式:
    一行四个数据,棋盘的大小和马的坐标

    输出格式:
    一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

    输入输出样例

    输入样例#1:
    3 3 1 1

    输出样例#1:
    0 3 2
    3 -1 1
    2 1 4
    .
    .
    .
    .
    .
    .
    .

    分析:

    这是一题十分耀眼的广搜!!!
    .
    .
    .
    .
    .
    .
    .

    程序:
    const
    dx:array[1..8] of longint=(2,1,-1,-2,-2,-1,2,1);
    dy:array[1..8] of longint=(-1,-2,-2,-1,1,2,1,2);
    var
    s:array[1..233,1..233] of longint;
    h:array[1..233333,1..2] of longint;
    bz:array[1..233,1..233] of boolean;
    n,m,x,y,i,j,p:longint;
    procedure bfs(c,d:longint);
    var
    i,j,t,w,x,y:longint;
    begin
        bz[c,d]:=false;
        t:=1; w:=1;
        h[t,1]:=c; h[t,2]:=d;
        s[c,d]:=1;
        repeat
             for i:=1 to 8 do
             begin
                 x:=h[t,1]+dx[i];
                 y:=h[t,2]+dy[i];
                 if (x>0)and(x<=n)and(y>0)and(y<=m)and bz[x,y] then
                 begin
                     inc(w);
                     h[w,1]:=x;
                     h[w,2]:=y;
                     bz[x,y]:=false;
                     s[x,y]:=s[h[t,1],h[t,2]]+1;
                 end;
             end;
             inc(t);
        until t>w;
    end;
    begin
        readln(n,m,x,y);
        fillchar(s,sizeof(s),0);
        fillchar(bz,sizeof(bz),true);
        bfs(x,y);
        for i:=1 to n do
        begin                                    
            for j:=1 to m do
            begin
                write(s[i,j]-1);
                if (s[i,j]-1<10)and(s[i,j]-1>=0)then write('    ');
                if ((s[i,j]-1<100)and(s[i,j]-1>=10))or(s[i,j]-1=-1) then write('   ');
                if (s[i,j]-1<1000)and(s[i,j]-1>=100) then write('  ');
                if s[i,j]-1>=1000 then write(' ');
            end;
            writeln;
        end;
    end.
    
  • 相关阅读:
    第三次作业
    C语言第二次作业
    第一次作业
    C语言第六次作业
    C语言第五次作业
    C语言第四次作业
    C语言第三次作业
    C语言第二次作业
    C语言第一次作业
    C语言学习笔记(6)
  • 原文地址:https://www.cnblogs.com/YYC-0304/p/9499994.html
Copyright © 2020-2023  润新知