题目描述
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
输入格式
一行四个数据,棋盘的大小和马的坐标
输出格式
一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
思路:bfs
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int mod = 1e9 + 7;
int n,m;
struct node{
int x,y,step;
};
int a[8] = {1,2,2,1,-1,-2,-2,-1};
int b[8] = {2,1,-1,-2,-2,-1,1,2};
queue<node>q;
int ans[410][410];
int vis[410][410];
void bfs(int x,int y)
{
node now;
now.x = x;
now.y = y;
now.step = 0;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
ans[now.x][now.y] = now.step;
vis[now.x][now.y] = -1;
for(int i = 0; i < 8; i++)
{
node next;
next.x = now.x + a[i];
next.y = now.y + b[i];
next.step = ans[now.x][now.y] + 1;
if(next.x >= 1&& next.x <= m&& next.y >= 1&& next.y <= n&&vis[next.x][next.y] == 0)
{
vis[next.x][next.y] = -1;
q.push(next);
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
int x,y;
scanf("%d%d",&x,&y);
memset(ans,-1,sizeof(ans));
bfs(y,x);//下载了一个测试点才知道这题x和y是反着来的
for(int j = 1; j <= n; j++)
{
for(int i = 1; i <= m; i++)
{
printf("%-5d",ans[i][j]);
}
printf("\n");
}
}