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 58 59 60 61 62 63
| #include <stdio.h> #include <stdbool.h> #define BOARD_SIZE 8
int dx[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int dy[] = { 1, 2, 2, 1, -1, -2, -2, -1 };
typedef struct { int x; int y; } Position;
bool isValidPosition(int x, int y) { return (x >= 0 && x < BOARD_SIZE&& y >= 0 && y < BOARD_SIZE); }
void findKnightTour(Position start) { int chessboard[BOARD_SIZE][BOARD_SIZE]; for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { chessboard[i][j] = -1; } } Position queue[BOARD_SIZE * BOARD_SIZE]; int front = 0; int rear = 0; queue[rear++] = start; chessboard[start.x][start.y] = 0; while (front != rear) { Position current = queue[front++]; for (int i = 0; i < 8; i++) { int nextX = current.x + dx[i]; int nextY = current.y + dy[i]; if (isValidPosition(nextX, nextY) && chessboard[nextX][nextY] == -1) { chessboard[nextX][nextY] = chessboard[current.x][current.y] + 1; Position next = { nextX, nextY }; queue[rear++] = next; } } } printf("马踏棋盘的路径为:\n"); for (int i = 0; i < BOARD_SIZE; i++) { for (int j = 0; j < BOARD_SIZE; j++) { printf("%2d ", chessboard[i][j]); } printf("\n"); } } int main() { Position start = { 0, 0 }; findKnightTour(start); return 0; }
|