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.
1def validate_board(self, board, row, col):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 row_it in range(row):
3 if board[row_it][col] == 'Q':
4 return FalseWe 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 duplicaterow_block = row - row%3col_block = col - col%3for row_it in range(3): for col_it in range(3): if board[row_block+row_it][col_block+col_it] == val: return False# Check if second diagonal is validfor row_it, col_it in zip(reversed(range(row)), range(col+1, len(board))): if board[row_it][col_it] == 'Q': return False