视频讲解
P1443
#include
using namespace std;
using ll = long long;
int n,m,x,y;
int d[410][410];
bitset<410> vis[410];
int dx[] = {1,2,1,2,-1,-1,-2,-2};
int dy[] = {-2,-1,2,1,2,-2,1,-1};
//马的几种跳法
bool inmap(int x,int y){
return x >= 1 && x <= n && y >= 1 && y <= m;
}
void bfs(int x,int y){
queue> q;//一次可以存两数到queue中
memset(d,-1,sizeof(d));//初始化为-1
q.push({x,y});
d[x][y] = 0;
vis[x][y] = true;//表示已经走过初始点
while(q.size()){
int x1 = q.front().first;
int y1 = q.front().second;
q.pop();
for(int i = 0; i < 8; i++){
int x2 = x1 + dx[i];
int y2 = y1 + dy[i];
if(inmap(x2,y2) && vis[x2][y2] == false)
{
//在图中,并且第一次走到
d[x2][y2] = d[x1][y1] + 1;
vis[x2][y2] = true;
q.push({x2,y2});
}
}
}
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
cin >> n >> m >> x >> y;
bfs(x,y);//从x,y开始跳
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cout << d[i][j] << " ";
}
cout << '\n';
}
return 0;
}