我正在尝试编写一个可以部分解决问题并提供解决方案的函数 . 给我一块大小为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;
}