我正在尝试编写一个可以部分解决问题并给出解决方案的函数。 给我一块MxN大小的木板,在此情况下,我应尝试在K'的部分解的情况下放置K个皇后。
例如以下面板:
Q X * *
* * Q *
* * X *
* * X *
该功能应使用此板,行的索引1和列的索引2,其上的女王/王后数量-2,最终女王/王后数量-4。 我只允许在从colth列到该行末尾的rowth行上添加女王/王后, 以及任何列的任何后续行 在此示例中-(1,3),(2,0),(2,1),(2,2),(2,3),(3,0),(3,1),(3,2 ),(3,3) 该函数应打印true,因为可能会出现以下情况:
Q X * *
* * Q *
* * X *
* Q X Q
但是我的功能不能完全做到这一点,我也不明白为什么。
private static boolean kQueens(int[][] board, int k, int row, int col, int numOfQueens) {
if (numOfQueens == k) return true;
//trying to place a queen in the row at the col+1 ~ row length position.
// if possible place it and try to place a new one in the next position.
for (int i = 0; i < board.length; ++i) {
for (int j = 0; j < board[i].length; j++) {
//save the value of that position in case we'll need to change it back
int tmp = board[i][j];
if (addQueen(board, i, j)) {
board[i][j] = QUEEN;
}
if (kQueens(board, k, i, j, numOfQueens + 1)) {
return true;
}
//remove the queen and backtrack
board[i][j]=tmp;
}
}
return false;
}