ナイトツアーは以前に依頼されましたが、まだ問題があります。私はチェス盤のすべての細胞を訪問する再帰を試みていますが、私は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;
}
}
}
}
int型の配列はすでに初期化されていませんか?したがって、mainメソッドのinitializeChess()は不要です。 – FatTony
@FatTonyそれは正しいです;すでに使用されている配列をクリアしてからやり直す必要があるだけで、このプログラムではできません。 –