Board Validation Function
Before we implement the solver itself, we need to create a function that can be used to see if we can put a queen on a cell in the board. The function will take the board, a row, and a col to place into that cell of the board.
1function validateBoard(board, row, col) {
2}The function will first check if there is a Queen in the same column in the board. We can check this easily by looping through the rows one at a time. Notice that we do not need to check for queens after the current row because we have not reached that point yet. Here is the python code for this validation:
1// Check if row is valid
2for(let row_it = 0; row_it < row; row_it++){
3 if(board[row_it][col] == 'Q'){
4 return false;
5 }
6}We do not need to check for Queens in the same column because in the backtracking process, we will put only one Queen at each column.
Following this, we will check if a Queen appears in the first diagonal of the board. To do this, we will need to see how the row_it and the col_it variables in a loop increases or decreases. See the below image to understand it. The first one is for the first diagonal and the second one is for the second diagonal.


xxxxxxxxxx// Check if block has duplicatelet rowBlock = row - row % 3;let colBlock = col - col % 3;for (let rowIt = 0; rowIt < 3; rowIt++) { for (let colIt = 0; colIt < 3; colIt++) { if (board[rowBlock + rowIt][colBlock + colIt] === val) { return false; } }}​// Check if second diagonal is validfor (let rowIt = row - 1, colIt = col + 1; rowIt >= 0 && colIt < board.length; rowIt--, colIt++) { if (board[rowIt][colIt] === 'Q') { return false; }}

