马的遍历
题目描述
有一个 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。
code:
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
typedef pair<int ,int > PII;
const int N=410;
int n,m,x,y;
int dist[N][N];
queue<PII>q;
int dx[]={2,2,1,1,-1,-1,-2,-2},dy[]={1,-1,2,-2,2,-2,1,-1};
void bfs(int x,int y){
memset(dist,-1,sizeof(dist));
q.push({x,y});
dist[x][y]=0;
while(!q.empty()){
auto t=q.front();
q.pop();
for(int i=0;i<8;i++){
int a=t.first+dx[i];
int b=t.second+dy[i];
if(a<1||a>n||b<1||b>m) continue;
if(dist[a][b]>=0) continue;
dist[a][b]=dist[t.first][t.second]+1;
q.push({a,b});
}
}
}
int main(){
cin>>n>>m>>x>>y;
bfs(x,y);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
printf("%-5d",dist[i][j]);
}
cout<<endl;
}
return 0;
}