输入:6 9 1 1 答案:
0 3 2 3 2 3 4 5 4
3 4 1 2 3 4 3 4 5
2 1 4 3 2 3 4 5 4
3 2 3 2 3 4 3 4 5
2 3 2 3 4 3 4 5 4
3 4 3 4 3 4 5 4 5
我的代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,m,x,y,vis[420][420];
int dx[10]={-2,-2,-1,-1,2,2,1,1};
int dy[10]={1,-1,2,-2,1,-1,2,-2};
struct two{
int a,b;
};
queue<two> q;
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n>>m>>x>>y;
q.push((two){x,y});
memset(vis,-1,sizeof(vis));
vis[x][y]=0;
while(!q.empty()){
int xx=q.front().a;
int yy=q.front().b;
q.pop();
for(int i=0;i<8;i++){
int xa=xx+dx[i];
int ya=yy+dy[i];
if(vis[xa][ya]==-1 and (xa>=0 and xa<=n) and (ya>=0 and ya<=m)){
vis[xa][ya]=vis[xx][yy]+1;
q.push((two){xa,ya});
}
}
}for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cout<<setw(5)<<left<<vis[i][j];
}cout<<endl;
}
return 0;
}