RT,可能明天晚上才能回复及关注。
#include <bits/stdc++.h>
using namespace std;
struct Pos{
int x,y,step;
Pos(int ax=0,int ay=0,int astep=0){
x=ax,y=ay,step=astep;
}
};
queue <Pos> q;
int n,m;
bool vis[402][402];
int a[402][402];
int go[9][2]={
{0,0},
{-1,-2},
{-2,-1},
{-2,1},
{-1,2},
{1,2},
{2,1},
{2,-1},
{1,-2}
};
void bfs(){
while(!q.empty()) {
Pos now=q.front();
q.pop();
int x=now.x,y=now.y,step=now.step;
a[x][y]=step;
for(int i=1; i<=8; i++){
int x1=x+go[i][1],y1=y+go[i][2];
if(x1>=1 && x1<=n && y1>=1 && y1<=m && !vis[x1][y1]){
vis[x1][y1]=true;
q.push(Pos(x1,y1,step+1));
}
}
}
}
/*void out(int s){
if(!s){
cout<<"0 ";
return ;
}
int w=5,q=s;
while(q>0){w--,q/=10;}
cout<<s;
for(int i=1; i<=w; i++) cout<<" ";
}*/
int main(){
int xx,yy;
cin>>n>>m>>xx>>yy;
q.push(Pos(xx,yy,0));
bfs();
for(int i=1; i<=n; i++){
for(int j=1; j<=m; j++){
if(!vis[i][j]) printf("-1 ");
else printf("%-5d",a[i][j]);
}
printf("\n");
}
return 0;
}