<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>

<p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" style="width: 600px; height: 268px;" />
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 9</code></li>
</ul>

class Solution:
    def totalNQueens(self, n: int) -> int:
        # Define sets to track column and diagonal conflicts
        cols = set()           # Columns that are attacked by queens
        diag1 = set()          # Primary diagonal (r - c)
        diag2 = set()          # Secondary diagonal (r + c)
        
        # Function to perform backtracking
        def backtrack(row):
            # If we have successfully placed queens on all rows, it's a valid solution
            if row == n:
                return 1
            
            solutions = 0
            for col in range(n):
                # Check if the current column or diagonals are under attack
                if col in cols or (row - col) in diag1 or (row + col) in diag2:
                    continue
                
                # Place a queen by marking the column and diagonals
                cols.add(col)
                diag1.add(row - col)
                diag2.add(row + col)
                
                # Move to the next row and accumulate the number of solutions
                solutions += backtrack(row + 1)
                
                # Backtrack: remove the queen and undo the markings
                cols.remove(col)
                diag1.remove(row - col)
                diag2.remove(row + col)
            
            return solutions
        
        # Start the backtracking process from the first row
        return backtrack(0)
16200