棋盘上的马
2025-01-24 11:18:24
发布于:上海
#include<bits/stdc++.h>
using namespace std;
struct node{
int x,y;
};
int n,m,sx,sy;
int d[500][500];
int to[8][2] = {1,2,2,1,-1,2,2,-1,-1,-2,-2,-1,1,-2,-2,1};
bool vis[500][500];
queue<node> q;
bool check(int x,int y){
return x>=1&&x<=n&&y>=1&&y<=m;
}
void bfs(int x,int y){
vis[x][y] = true;
q.push({x,y});
d[x][y] = 0;
while(q.size()){
node t = q.front();
q.pop();
for(int i = 0;i<8;i++){
int nx = t.x + to[i][0];
int ny = t.y + to[i][1];
if(check(nx,ny)&&!vis[nx][ny]){
vis[nx][ny] = true;
q.push({nx,ny});
d[nx][ny] = d[t.x][t.y] + 1;
}
}
}
}
int main(){
cin>>n>>m>>sx>>sy;
bfs(sx,sy);
for(int i = 1;i<=n;i++){
for(int j = 1;j<=m;j++){
if(vis[i][j]) cout<<setw(5)<<left<<d[i][j];
else cout<<setw(5)<<left<<-1;
}
cout<<endl;
}
return 0;
}
这里空空如也
有帮助,赞一个