上课老师给了AC代码,看不懂,求解
#include <bits/stdc++.h>
using namespace std;
int dx[] = {-2, -1, 1, 2, 2, 1, -1, -2};
int dy[] = {1, 2, 2, 1, -1, -2, -2, -1};
int n, m, sx, sy, ans[405][405];
bool vis[405][405];
struct node {
int x, y, step;//坐标和步数
};
bool check(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= m;
}
void bfs() {
queue<node> q;//存储的是一个结构体
vis[sx][sy] = true;//标记走过
ans[sx][sy] = 0;//记录步数
q.push((node){sx, sy, 0});
while (!q.empty()) {
node tmp = q.front();
q.pop();
int x = tmp.x, y = tmp.y, step = tmp.step;
for (int i = 0; i < 8; i ++) {//枚举马的8个方向
int nx = x + dx[i], ny = y + dy[i];
if (check(nx, ny) && !vis[nx][ny]) {//可以访问
vis[nx][ny] = true;
ans[nx][ny] = step + 1;
q.push((node){nx, ny, step + 1});
}
}
}
}
int main() {
cin >> n >> m >> sx >> sy;
memset(vis, false, sizeof(vis));
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j ++) ans[i][j] = -1;
}
bfs();
for (int i = 1; i <= n; i ++) {
for (int j = 1; j <= m; j ++) {
printf("%-5d", ans[i][j]);
}
cout << endl;
}
return 0;
}
~~求dalao解析~~~