之前有人问过骑士的巡回演出,但我仍然遇到问题。我正在尝试递归访问棋盘的所有单元格,但访问次数不能超过 52 次。之后,它回溯并且访问的单元格的数量倒计时。这是我的代码:
public class Ch7E22_3 {
public static int[][] chess;
public static int[][] adjacent;
public static void main(String[] args) {
chess = new int[8][8];
adjacent = new int[][] { { 2, 1 }, { 2, -1 }, { -2, 1 }, { -2, -1 }, { 1, 2 }, { -1, 2 }, { 1, -2 },
{ -1, -2 } };
initializeChess();
move(1, 0, 0);
}
private static void move(int cnt, int row, int col) {
chess[row][col] = cnt;
if (cnt == (8 * 8)) {
System.out.println("You moved around all cells: " + cnt);
} else {
for (int i = 0; i < 8; i++) {
if (((row + adjacent[i][0] >= 0) && (row + adjacent[i][0]) < 8)
&& ((col + adjacent[i][1] >= 0) && (col + adjacent[i][1] < 8))) {
if (chess[row + adjacent[i][0]][col + adjacent[i][1]] == 0) {
row = row + adjacent[i][0];
col = col + adjacent[i][1];
cnt++;
System.out.println(row + " " + col + " cnt = " + cnt);
move(cnt, row, col);
}
}
}
}
chess[row][col] = 0;
}
private static void initializeChess() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
chess[i][j] = 0;
}
}
}
}