这是我的递归函数,用于解决N-Queens
问题,该问题要求在棋盘上找到皇后配置的数量,使得它们不能相互攻击。在validPosition
的帮助下,此函数成功地为每个N值输入基本案例(curRow == N)
适当的次数。但是,我不知道如何提取此信息。如果函数进入基本情况10次,则此函数应返回10.
但是,让它返回布尔值是在递归调用上有条件地分支的技术。是否有一个干净且一致的方法来输入基本情况正确的次数,并成功地将该信息传播到根函数调用并将其返回给调用者?
static boolean findNQueensSolutions(int N, int curRow, int[][] board, int result) {
if (curRow == N) {
return true;
}
for (int curCol = 0; curCol < N; curCol++) {
if (validPosition(board, curRow, curCol, N)) {
board[curRow][curCol] = 1;
if (findNQueensSolutions(N, curRow + 1, board, result)) {
return true;
}
board[curRow][curCol] = 0;
}
}
return false;
}
答案 0 :(得分:1)
您需要收集有关成功职位的信息,例如:
static int findNQueensSolutions(int N, int curRow, int[][] board) {
if (curRow == N)
return 1; // found 1 position
int result = 0; // found 0 positions yet
for (int curCol = 0; curCol < N; curCol++)
if (validPosition(board, curRow, curCol, N)) {
board[curRow][curCol] = 1;
result += findNQueensSolutions(N, curRow + 1, board); // do not return immediately, maybe there are more?
board[curRow][curCol] = 0;
}
return result;
}