一.题目描述
有一个 n×m 的棋盘,在某个点 (x, y)上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
## 输入格式
输入只有一行四个整数,分别为 n, m, x, y。
## 输出格式
一个 n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 -1)。
## 样例 #1
### 样例输入 #1
3 3 1 1
## 样例输出 #1
0 3 2
3 -1 1
2 1 4
## 提示
### 数据规模与约定
对于全部的测试点,保证 1≤x≤n≤400,1≤y≤m≤400。
二.解题思路
利用bfs进行遍历,初始化二维数组为-1,用二维数组存储到达每个点的步数。
三.代码展示
#include<iostream>//P1443 马的遍历lg
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int ,int> pll;//pair类型可以存放两个值,这里用来存储坐标。
queue<pll>q;//定义pair类型容器,或者可以用二维数组存储坐标
int n,m,x,y,x1,y1;
int a[410][410];//用来存储步数
void bfs(int ,int);
int dx[8]={2,2,-2,-2,1,1,-1,-1};//
int dy[8]={-1,1,-1,1,-2,2,-2,2};//方向遍历
int main()
{
cin>>n>>m>>x>>y;
bfs(x,y);
return 0;
}
void bfs(int x,int y)
{
memset(a,-1,sizeof a);//初始化步数
a[x][y]=0;//初始化起点位置
q.push({x,y});
while(!q.empty())//判断是否遍历完
{
pll p=q.front();
q.pop();//将所在点位,出队,进行方向遍历
for(int i=0;i<8;i++)
{
x1=dx[i]+p.first;
y1=dy[i]+p.second;
if(a[x1][y1]>=0)continue;
if(x1<1||x1>n||y1<1||y1>m)continue;
a[x1][y1]=a[p.first][p.second]+1;//记录步数
q.push({x1,y1});
}
}for(int i=1;i<=n;i++)
{ for(int j=1;j<=m;j++)
{
cout<<a[i][j]<<" ";
}cout<<endl;
}
}