马的遍历题解
2025-07-25 17:28:51
发布于:浙江
#include <bits/stdc++.h>
using namespace std;
int dr[][2]={-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2},mp[450][450],n,m,sx,sy;
struct node {
int x,y,step;
};
void bfs(int x , int y){
memset(mp,-1,sizeof(mp));
queue <node> q;
q.push({x,y,0});
mp[x][y]=0;
while (q.size()){
node u=q.front();
q.pop();
for (int i=0;i<8;i++){
int nx=u.x+dr[i][0],ny=u.y+dr[i][1];
if (nx>=1 && nx <= n && ny>=1 && ny<=m && mp[nx][ny]==-1){
mp[nx][ny]=u.step+1;
q.push({nx,ny,u.step+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++){ cout<<mp[i][j]<<" ";
}
cout<<endl;
}
}
这里空空如也
有帮助,赞一个