所以我正在尝试解决 n-queens 问题。我认为我有一个有效的回溯实现,但我认为我检查板是否有效的方法已关闭(并且效率极低),但我不明白为什么。谁能明白为什么/提供更好的方法?
/** Given an N x N chess board, find placements for N queens on the board such that
* none of them are attacking another queen (two queens are attacking each other if
* they occupy the same row, column, or diagonal).
* Print out the row, col coordinates for each queen on a separate line, where the
* row and column numbers are separated by a single space. */
static void solveQueens(int n) {
boolean[][] board = new boolean[n][n];
board = solveQueens(board, n);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j]) {
System.out.printf("%s %s\n", i, j);
}
}
}
}
/** Returns a solved board for the n-queens problem, given an empty board. */
static boolean[][] solveQueens(boolean[][] board, int queensLeft) {
if (queensLeft == 0) {
return board;
}
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j]) { continue; }
board[i][j] = true;
if (isValid(board)) {
return solveQueens(board, queensLeft - 1);
} else {
board[i][j] = false;
}
}
}
return null;
}
/** True iff BOARD is a valid solution, with no queens attacking each other. */
static boolean isValid(boolean[][] board) {
boolean occupied = false;
//Horizontal
for (int i = 0; i < board.length; i++) {
for (boolean queen : board[i]) {
if (queen && occupied) {
return false;
}
if (queen) {
occupied = true;
}
}
occupied = false;
}
//Vertical
for (int i = 0; i < board.length; i++) {
for (int j = board.length - 1; j >= 0; j--) {
boolean queen = board[j][i];
if (queen && occupied) {
return false;
}
if (queen) {
occupied = true;
}
}
occupied = false;
}
//Diagonals
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[i][j]) {
for (int k = 0; k < board.length; k++) {
for (int l = 0; l < board.length; l++) {
if (((i - k) == (j - l)) && board[k][l] && !(k == i && l == j)) {
return false;
}
}
}
}
}
}
return true;
}