题目:
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n,m;
int dx[] = {-1,-1,-2,-2,1,1,2,2};
int dy[] = {-2,2,-1,1,-2,2,-1,1};
bool vis[450][450];
struct node{
int x,y;
};
int sx,sy;
int mp[450][450] = {-1}; //将路径存在mp里
void bfs(int xx,int yy){
queue<node> q;
q.push({xx,yy});
vis[xx][yy] = true;
mp[xx][yy] = 0;
while(!q.empty()){
node temp = q.front();
q.pop();
for(int i=0;i<8;i++){
int nx = dx[i] + temp.x;
int ny = dy[i] + temp.y;
if(nx > n || nx <= 0 || ny > m || ny <= 0) continue;
if(vis[nx][ny]) continue;
if(!vis[nx][ny]){
vis[nx][ny] = true;
mp[nx][ny] = mp[temp.x][temp.y] + 1;
q.push({nx,ny});
}
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
printf("%d ",mp[i][j]);
}
printf("\n");
}
}
int main()
{
scanf("%d%d%d%d",&n,&m,&sx,&sy);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
mp[i][j] = -1;
}
}
bfs(sx,sy);//要从x,y到达每一个点,不能到达赋值-1
//用队列,地图赋值-1
return 0;
}
结果: