Your task is to write a program to calculate the minimum number of moves needed for a knight to reach one point from another. The possible knight moves are shown in Figure 1. node
Figure 1 Possible knight moves on the board ios
The first line contains an integer T (≤10), indicating the number of test cases. spa
In every case, the first line contains an integer N (≤500), indicating the size of the chess board (the entire board has size N × N). The second and third line contain pair of integers (srcR, srcC), and (dstR, dstC), specifying the starting and ending position of the knight on the board (0 ≤ srcR, srcC, dstR, dstC ≤ N – 1). code
For every case, output the minimum distance on a single line. If starting point and ending point are equal, distance is 0. If the knight can’t reach the ending point, distance is -1. orm
2 1 0 0 0 0 10 0 1 8 9
0 6
簡單的BFS查找,注意判斷狀態是否合法便可。 ip
// Problem#: 1781 // Submission#: 1896080 // The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License // URI: http://creativecommons.org/licenses/by-nc-sa/3.0/ // All Copyright reserved by Informatic Lab of Sun Yat-sen University #include <iostream> #include <queue> #include <cstring> using namespace std; #define MAX 500 struct node{ int x, y, z; node(int r, int s, int t){ x = r; y = s; z = t; } }; int n, a, b, c, d; bool visit[MAX][MAX]; int move[8][2] = {{-2, -1}, {-1, -2}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {1, -2}, {2, -1}}; inline bool judge(int x, int y){ return x >= 0 && x < n && y >= 0 && y < n; } int bfs(){ queue<node> buffer; memset(visit, false, sizeof(visit)); buffer.push(node(a, b, 0)); visit[a][b] = true; while (!buffer.empty()) { node tmp = buffer.front(); if (tmp.x == c && tmp.y == d) return tmp.z; buffer.pop(); for (int i = 0 ; i < 8 ; ++i) { int tx = tmp.x + move[i][0]; int ty = tmp.y + move[i][1]; int tz = tmp.z + 1; if (judge(tx, ty) && !visit[tx][ty]){ buffer.push(node(tx, ty, tz)); visit[tx][ty] = true; } } } return -1; } int main() { int t; cin >> t; while (t--) { cin >> n; cin >> a >> b >> c >> d; cout << bfs() << endl; } return 0; }