NQueens問題の再帰プログラムを、指定されたボードサイズで作成しています。私の問題は、女王はボードに置かれていないと私はなぜわからないです。私はプログラムをトレースしようとしましたが、私はまだ私の問題を見ていません。助言がありますか?NQueensパズル、女王は置いていない?
public class Main {
public static boolean[][] board;
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Enter size of board");
int n = scan.nextInt();
board = new boolean[n][n];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
board[i][j] = false;
}
}
NQueens(0);
printBoard();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == true) {
System.out.println((i + 1) + " " + (j + 1));
}
}
}
}
static boolean NQueens(int col) {
if (col >= board.length)
return true;
for (int i = 0; i < board.length; i++) {
if (checkNotBlocked(col, i)) {
board[col][i] = true;
if (NQueens(col + 1))
return true;
board[col][i] = false;
}
}
return false;
}
static boolean checkNotBlocked(int col, int row) {
for (int i = 0; i < col; i++) {
if (board[i][row] == true)
return false;
}
for (int i = col; i >= 0; i--) {
for (int j = row; j >= 0; j--) {
if (board[i][j] == true)
return false;
}
}
for (int i = col; i >= 0; i--) {
for (int j = row; j < board.length; j++) {
if (board[i][j] == true)
return false;
}
}
return true;
}
static void printBoard() {
int i;
for (i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j] == true) {
System.out.print("Q\t");
} else {
System.out.print("_\t");
}
}
System.out.println("\n");
}
}
ベスト・ベット:デバッガを使ってプログラムを実行し、実行中の動作を確認します。 –
これは本当に答えていないようです –