1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <cstdio> #include <cstring> #include <queue> #define MAX_LEN 300
typedef struct Knight { int X; int Y; int dist; };
int direction[8][2] = { {2,1}, {1,2}, {-1,2}, {-2,1}, {-2,-1}, {-1,-2}, {1,-2}, {2,-1} };
int main() { int testNum; scanf("%d", &testNum); while(testNum--) { int boardLen, startX, startY, endX, endY; scanf("%d", &boardLen); scanf("%d %d", &startX, &startY); scanf("%d %d", &endX, &endY);
bool board[MAX_LEN+2][MAX_LEN+2]; memset(board, false, sizeof(board)); std::queue<Knight> q; q.push(Knight{startX, startY, 0});
while(!q.empty()) { Knight topKnight = q.front(); board[topKnight.X][topKnight.Y] = topKnight.dist; if(topKnight.X == endX && topKnight.Y == endY) { printf("%d\n", topKnight.dist); break; } for(int i = 0; i < 8; i++) { int tempX = topKnight.X + direction[i][0]; int tempY = topKnight.Y + direction[i][1]; if(tempX >= 0 && tempX < boardLen && tempY >= 0 && tempY < boardLen) { if(!board[tempX][tempY]) { q.push(Knight{tempX, tempY, topKnight.dist + 1}); board[tempX][tempY] = true; } } } q.pop(); } } }
|