Knight's Tour wurde vorher gefragt, aber ich habe immer noch Probleme damit. Ich versuche eine Rekursion, um alle Zellen des Schachbretts zu besuchen, aber ich kann nicht mehr als 52 Besuche machen. Danach rückt es zurück und die Anzahl der besuchten Zellen zählt herunter. Hier ist mein Code:Knight's Tour Rekursion findet keine Lösung
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;
}
}
}
}
Weiß nicht sicher, aber ist nicht initialisiert int Array bereits mit Nullen gefüllt? So ist die initializeChess() in Ihrer Hauptmethode unnötig. – FatTony
@FatTony Das ist richtig; es wäre nur erforderlich, ein bereits verwendetes Array zu löschen und neu zu starten, was dieses Programm nicht tut. –