生成一段马踏棋盘算法Java代码
时间: 2023-04-04 12:05:04 浏览: 118
以下是一段马踏棋盘算法的 Java 代码:
```
public class HorseChessboard {
private int[][] chessboard;
private int startX;
private int startY;
private int stepCount;
private boolean finished;
public HorseChessboard(int n) {
this.chessboard = new int[n][n];
}
public void printChessboard() {
for (int[] row : chessboard) {
for (int num : row) {
System.out.print(num + "\t");
}
System.out.println();
}
}
public void horseTravel(int x, int y) {
chessboard[x][y] = ++stepCount;
if (stepCount == chessboard.length * chessboard.length) {
finished = true;
return;
}
int[][] nextMoves = getNextMoves(x, y);
for (int[] nextMove : nextMoves) {
int nextX = nextMove[0];
int nextY = nextMove[1];
if (chessboard[nextX][nextY] == 0) {
horseTravel(nextX, nextY);
}
}
if (!finished) {
chessboard[x][y] = 0;
stepCount--;
}
}
private int[][] getNextMoves(int x, int y) {
int[][] nextMoves = new int[8][2];
int count = 0;
if (canMove(x - 2, y - 1)) {
nextMoves[count++] = new int[]{x - 2, y - 1};
}
if (canMove(x - 1, y - 2)) {
nextMoves[count++] = new int[]{x - 1, y - 2};
}
if (canMove(x + 1, y - 2)) {
nextMoves[count++] = new int[]{x + 1, y - 2};
}
if (canMove(x + 2, y - 1)) {
nextMoves[count++] = new int[]{x + 2, y - 1};
}
if (canMove(x + 2, y + 1)) {
nextMoves[count++] = new int[]{x + 2, y + 1};
}
if (canMove(x + 1, y + 2)) {
nextMoves[count++] = new int[]{x + 1, y + 2};
}
if (canMove(x - 1, y + 2)) {
nextMoves[count++] = new int[]{x - 1, y + 2};
}
if (canMove(x - 2, y + 1)) {
nextMoves[count++] = new int[]{x - 2, y + 1};
}
return Arrays.copyOfRange(nextMoves, 0, count);
}
private boolean canMove(int x, int y) {
return x >= 0 && x < chessboard.length && y >= 0 && y < chessboard.length;
}
public static void main(String[] args) {
HorseChessboard horseChessboard = new HorseChessboard(8);
horseChessboard.horseTravel(0, 0);
horseChessboard.printChessboard();
}
}
```
阅读全文