C-马的遍历
题目
有一个 n ×m 的棋盘,在某个点 (x, y)上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。
输入格式
输入只有一行四个整数,分别为 n, m, x, yn,m,x,y。
输出格式
一个 n×m 的矩阵,代表马到达某个点最少要走几步(不能到达则输出−1)。
Sample Input:
3 3 1 1
Sample Output:
0 3 2
3 -1 1
2 1 4
思路
主要思路是模拟马的走法,即马走日(一共有8种走法),用bfs考虑8个方向套模板就行。
代码
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
const int N=110;
int px[]={-2,-1,-2,-1,2,1,2,1};//模拟8种走法
int py[]={-1,-2,1,2,-1,-2,1,2};
struct node{
int x,y,step;
}xy,top;
queue<node>q;
int ans[410][410];
bool flag[410][410];
int n,m,x0,y0;
void bfs(int x,int y,int step){
ans[x][y]=step;
flag[x][y]=false;
xy.x=x;
xy.y=y;
q.push(xy);
while(!q.empty()){
top=q.front();
q.pop();
for(int i=0;i<8;i++){
int tx=top.x+px[i];
int ty=top.y+py[i];
if(tx>0&&tx<=n&&ty>0&&ty<=m){
if(flag[tx][ty]){
xy.x=tx;
xy.y=ty;
q.push(xy);//入队
ans[tx][ty]=ans[top.x][top.y]+1;//更新答案
flag[tx][ty]=false;
}
}
}
}
}
int main(){
cin>>n>>m>>x0>>y0;
memset(ans,-1,sizeof(ans));
memset(flag,true,sizeof(flag));
bfs(x0,y0,0);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cout<<ans[i][j]<<" ";
}
cout<<endl;
}
return 0;
}