그래서 n-queens 문제를 해결하려고합니다. 내가 유효한 backtracking 구현을 가지고 있다고 생각하지만, 보드가 유효한지 검사하는 나의 방법은 (물론 비효율적 일뿐만 아니라) 꺼져 있다고 생각하지만, 나는 그 이유를 알 수 없다. 누구든지 왜 볼 수 있습니까/더 나은 방법을 제공합니까? 대신 매우 비효율적 각 광장 (2^(n*n)
)의 여왕을 배치하려고 노력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;
}
넵! 정말 고맙습니다! – BrandonM
하하 문제 없음 =) – yanhan