通过广搜, 向如图所示的8个方向搜索, 边搜索边记录步数, 最后若到达终点则返回当前走过的步数, 否则返回0
#include <iostream> #include <queue> #include <cstring> using namespace std; struct node { int x, y; // 当前点的坐标 int step; // 当前走的步数 node() {} node(int x1, int y1):x(x1), y(y1) {} }; int n, l; int map[310][310], vis[310][310]; int dir[8][2] = {{2,1},{1,2},{-1,2},{-2,1},{-1,-2},{-2,-1},{1,-2},{2,-1}}; node s, e; int bfs() { queue<node> q; node p, t; int dx, dy; s.step = 0; vis[s.x][s.y] = 1; q.push(s); while(!q.empty()) { p = q.front(); q.pop(); if(p.x == e.x && p.y == e.y) return p.step; for(int i = 0; i < 8; ++ i) { dx = p.x + dir[i][0]; dy = p.y + dir[i][1]; if(dx < 0 || dx >= l || dy < 0 || dy >= l || vis[dx][dy]) continue; t = node(dx, dy); t.step = p.step + 1; vis[t.x][t.y] = 1; q.push(t); } } return 0; } int main() { cin >> n; while(n --) { memset(vis, 0, sizeof(vis)); cin >> l; cin >> s.x >> s.y; cin >> e.x >> e.y; cout << bfs() << endl; } return 0; } /* Sample Input: 3 8 0 0 7 0 100 0 0 30 50 10 1 1 1 1 Sample Output: 5 28 0 */