Recursive Backtracking
For the backtracking, we will take each row
and put a Queen in a feasible place (with the help of validate_board
) in that row
. After placing the Queen, we will recursively continue from the next row in the board.
After finishing that recursive function, we will have all the solved boards, putting a Queen at that row
and col
. We'll need the next step of putting current Queen in the next feasible place. That is why we will pick up the Queen (put '.' there) and continue the loop.
Finally there will be all the solutions in res
. Also, we will again be at the top of the call stack in the recursive function. So we will return our desired res
to the caller function.
xxxxxxxxxx
for(let col = 0; col < board.length; col++) {
if(this.validate_board(board, row, col)) {
// Put a queen and move forward
board[row] = board[row].substr(0, col) + "Q" + board[row].substr(col+1);
this.recursiveSolveNQueens(res, board, row+1);
// Now backtrack
board[row] = board[row].substr(0, col) + "." + board[row].substr(col+1);
}
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment