题目分析
bfs宽度优先搜索
代码
#include#include #include using namespace std; int t, n; int sx, sy, ex, ey, nx, ny; int book[305][305]; int dir[8][2] = { {2,-1},{2,1},{1,-2},{1,2},{-1,2},{-1,-2},{-2,-1},{-2,1} }; struct knight { int x; int y; int step; }fa, son; void bfs(int sx, int sy) { queue q; int x, y, step; fa.x = sx; fa.y = sy; fa.step = 0; q.push(fa); memset(book,0, sizeof(book)); while (!q.empty()) { knight fa = q.front(); q.pop(); if (fa.x == ex && fa.y == ey) { cout << fa.step << endl; break; } for (int k = 0; k < 8; k++) { nx = fa.x + dir[k][0]; ny = fa.y + dir[k][1]; if (nx >= 0 && ny >= 0 && nx < n && ny < n && book[nx][ny] == 0) { knight son; son.x = nx; son.y = ny; son.step = fa.step + 1; book[nx][ny] = 1; q.push(son); } } } } int main() { cin >> t; while (t--) { cin >> n; cin >> sx >> sy >> ex >> ey; bfs(sx, sy); } return 0; }



