This is my recursive function to solve the N-Queens
problem that asks to find the number of configurations of queens on a chess board such that they cannot attack each other. With the help of validPosition
this function successfully enters the base case (curRow == N)
the proper number of times for each value of N. However, I am unclear as to how to extract this information. If the function enters the base case 10 times than this function should return 10.
But, having it return boolean is the technique for conditionally branching on its recursive call. Is there a clean and consistent method to both enter the base case the correct number of times and also successfully propagate that information up to the root function call and return it to the caller?
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;
}
you need to collect information about successful positions, like this:
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;
}