骑士游历,使用栈,寻找5*5的解。Java
时间: 2024-04-08 16:30:50 浏览: 75
以下是使用栈来寻找5*5棋盘上骑士游历的解的Java代码示例:
```java
import java.util.*;
public class KnightTour {
private static int BOARD_SIZE = 5;
private static int[][] board;
private static int[] moveX = {2, 1, -1, -2, -2, -1, 1, 2};
private static int[] moveY = {1, 2, 2, 1, -1, -2, -2, -1};
public static void main(String[] args) {
board = new int[BOARD_SIZE][BOARD_SIZE];
solveKnightTour();
}
public static void solveKnightTour() {
// 初始化棋盘
for (int i = 0; i < BOARD_SIZE; i++) {
Arrays.fill(board[i], -1);
}
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{0, 0});
board[0][0] = 0;
while (!stack.isEmpty()) {
int[] current = stack.pop();
int x = current[0];
int y = current[1];
int moveCount = board[x][y];
if (moveCount == BOARD_SIZE * BOARD_SIZE - 1) {
// 找到了解
printSolution();
return;
}
for (int i = 0; i < moveX.length; i++) {
int nextX = x + moveX[i];
int nextY = y + moveY[i];
if (isValidMove(nextX, nextY) && board[nextX][nextY] == -1) {
stack.push(new int[]{nextX, nextY});
board[nextX][nextY] = moveCount + 1;
}
}
}
System.out.println("无解");
}
public static boolean isValidMove(int x, int y) {
return x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE;
}
public static void printSolution() {
for (int i = 0; i < BOARD_SIZE; i++) {
for (int j = 0; j < BOARD_SIZE; j++) {
System.out.print(board[i][j] + "\t");
}
System.out.println();
}
}
}
```
这个代码示例使用了一个二维数组`board`来表示棋盘,初始化为-1。通过使用栈来进行深度优先搜索,找到一条解路径后,会打印出解的矩阵。
请注意,这只是一个简单的示例,针对5*5棋盘的解。如果你需要针对其他棋盘大小的解,请相应地调整`BOARD_SIZE`和相关的移动数组。
阅读全文