P1443 马的遍历

P1443 马的遍历

题目描述

有一个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    
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>

using namespace std;
const int N=401;
const int xd[]={-1,-2,-2,-1,1,2,2,1};
const int yd[]={-2,-1,1,2,2,1,-1,-2};

struct node{
    int x,y,step;
}now,top,nxt;
queue<node>q;
int ans[N][N];
int n,m,startx,starty;

inline int read()
{
    int x=0;char c=getchar();
    while(c<'0'||c>'9')c=getchar();
    while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();
    return x;
}

inline void bfs(int x,int y)
{
    ans[x][y]=-3;
    now.x=x;
    now.y=y;
    now.step=0;
    q.push(now);
    while(!q.empty())
    {
        top=q.front();
        q.pop();
        for(int i=0;i<8;i++)
        {
            int x=top.x+xd[i];
            int y=top.y+yd[i];
            if(x>0&&x<=n&&y>0&&y<=m&&!ans[x][y])
            {
                ans[x][y]=top.step+1;
                nxt.x=x;
                nxt.y=y;
                nxt.step=top.step+1;
                q.push(nxt);
            }
        }
    }
}

int main()
{
    n=read();
    m=read();
    startx=read();
    starty=read();
    bfs(startx,starty);
    
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(ans[i][j]==-3)
                printf("%-5d",0);
            else if(ans[i][j]==0)
                printf("%-5d",-1);
            else printf("%-5d",ans[i][j]);
        }
        printf("
");
    }    

    return 0;
}


原文地址:https://www.cnblogs.com/lyqlyq/p/7086877.html