社区讨论
SOS!玄关求助
P1443马的遍历参与者 3已保存回复 2
讨论操作
快速查看讨论及其快照的属性,并进行相关操作。
- 当前回复
- 2 条
- 当前快照
- 1 份
- 快照标识符
- @m5upc5k7
- 此快照首次捕获于
- 2025/01/13 15:07 去年
- 此快照最后确认于
- 2025/11/04 11:40 4 个月前
CPP
#include <bits/stdc++.h>
using namespace std;
const int N = 505;
struct coord {
int x, y;
};
int a[N][N], n, m, sx, sy;
int walk[8][2] = {{2, 1}, {2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {-1, 2}, {-1, -2}, {1, -2}};
queue<coord>Q;
void bfs() {
while (!Q.empty()) {
coord u = Q.front();
Q.pop();
int ux = u.x, uy = u.y;
for (int i = 1; i <= 8; i++) {
int x = ux + walk[i][0], y = uy + walk[i][1];
int d = a[ux][uy];
if (x < 1 || x > n || y < 1 || y > m || a[x][y != -1]) {
continue;
}
a[x][y] = d + 1;
coord tmp = {x, y};
Q.push(tmp);
}
}
}
int main() {
memset(a, -1, sizeof(a));
cin >> n >> m >> sx >> sy;
coord tmp = {sx, sy};
Q.push(tmp);
a[sx][sy] = 0;
bfs();
for (int i = 1; i <= n; i++, puts(" ")) {
for (int j = 1; j <= m; j++) {
cout << setw(5) << a[i][j];
}
}
return 0;
}
回复
共 2 条回复,欢迎继续交流。
正在加载回复...