answers here!
2024-07-27 19:25:19
发布于:浙江
3阅读
0回复
0点赞
#include<bits/stdc++.h>
using namespace std;
int dir[8][2] = { -2, -1, -2, 1, -1, 2, 1, 2, 2, 1, 2, -1, 1, -2, -1, -2 };
struct data {
int x, y, step;
} l, r;
int sx, sy, ex, ey, n, m;
queue<data> q;
bool vis[301][301];
void bfs() {
while (q.size()) {
r = q.front();
q.pop();
if (r.x == ex && r.y == ey) {
cout << r.step << endl;
return;
}
for (int i = 0; i < 8; i++) {
l.x = r.x + dir[i][0];
l.y = r.y + dir[i][1];
l.step = r.step + 1;
if (l.x >= 0 && l.x < n && l.y >= 0 && l.y < n && !vis[l.x][l.y]) {
vis[l.x][l.y] = 1;
q.push(l);
}
}
}
}
int main() {
cin >> m;
while (m--) {
while (!q.empty()) q.pop();
memset(vis, 0, sizeof(vis));
cin >> n;
cin >> sx >> sy >> ex >> ey;
q.push({ sx, sy, 0 });
vis[sx][sy] = 1;
bfs();
}
return 0;
}
Hope you like it
give a thumbs up
这里空空如也
有帮助,赞一个