马的遍历
题目描述
有一个 n × m n \times m n×m 的棋盘,在某个点 ( x , y ) (x, y) (x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
输入格式
输入只有一行四个整数,分别为 n , m , x , y n, m, x, y n,m,x,y。
输出格式
一个 n × m n \times m n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出 − 1 -1 −1)。
样例 #1
样例输入 #1
3 3 1 1
样例输出 #1
0 3 2
3 -1 1
2 1 4
提示
数据规模与约定
对于全部的测试点,保证 1 ≤ x ≤ n ≤ 400 1 \leq x \leq n \leq 400 1≤x≤n≤400, 1 ≤ y ≤ m ≤ 400 1 \leq y \leq m \leq 400 1≤y≤m≤400。
思路
首先我们要知道马怎么走,下面是马可以走的位置图,红色是原来位置,黄色是可以走的点。
然后要找到最短路径,可以想到用bfs,找源点到任意一点的最短路径
以下是代码
代码
#include<bits/stdc++.h>
using namespace std;
int a[401][401]; //a[x][y]就是源点到这一点(x,y)的最短距离
int vis[401][401]; //用来标记
int dx[8]={2,1,-2,1,-1,-2,-1,2}; //可以走八个位置
int dy[8]={1,2,1,-2,-2,-1,2,-1};
int n,m;
struct node{
int x;
int y;
int step;
};
void bfs(int x,int y)
{
queue<node>q;
q.push({x,y,0});
a[x][y]=0;
vis[x][y]=1;
while(q.size())
{
int u=q.front().x,v=q.front().y,dd=q.front().step;
//cout<<u<<" "<<v<<" "<<"\n";
q.pop();
for(int i=0;i<8;i++)
{
int g=u+dx[i],h=v+dy[i];
if(g>n||h>m||g<1||h<1||vis[g][h]) continue;
else{
vis[g][h]=1;
a[g][h]=dd+1;
q.push({g,h,dd+1});
}
}
}
}
int main()
{
int x,y;
cin>>n>>m>>x>>y;
memset(a,-1,sizeof a); //初始化为-1,因为到达不了这点输出为-1
bfs(x,y);
for(int i=1;i<=n;i++) //输出
{
for(int j=1;j<=m;j++)
cout<<a[i][j]<<" ";
cout<<"\n";
}
}