<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>all distinct solutions to the <strong>n-queens puzzle</strong></em>. You may return the answer in <strong>any order</strong>.</p>

<p>Each solution contains a distinct board configuration of the n-queens&#39; placement, where <code>&#39;Q&#39;</code> and <code>&#39;.&#39;</code> both indicate a queen and an empty space, respectively.</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> [[&quot;.Q..&quot;,&quot;...Q&quot;,&quot;Q...&quot;,&quot;..Q.&quot;],[&quot;..Q.&quot;,&quot;Q...&quot;,&quot;...Q&quot;,&quot;.Q..&quot;]]
<strong>Explanation:</strong> There exist two distinct solutions to the 4-queens puzzle as shown above
</pre>

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

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[&quot;Q&quot;]]
</pre>

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

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

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:

        def backtrack(row, cur_board):

            # place queen row by row

            # return: when row = n, means all quees are placed correctly, this is a valid placement
            if row == n:
                # res.append([''.join(row) for row in cur_board])
                temp = []
                for cur_row in cur_board:
                    temp.append(''.join(cur_row)) # from to ".","Q",".","." to ".Q.."
                res.append(temp)
                return
            
            for col in range(n):
                # check if we can place a queen here
                if col in col_s or (row-col) in major_diag or (row+col) in minor_diag:
                    continue
                # we place a queen at (row, col)
                cur_board[row][col] = 'Q'
                col_s.add(col)
                major_diag.add(row-col)
                minor_diag.add(row+col)

                # based on this, place next queen to next row
                backtrack(row+1, cur_board)

                # backtrack
                cur_board[row][col] = '.'
                col_s.remove(col)
                major_diag.remove(row-col)
                minor_diag.remove(row+col)

        # define the attack place
        col_s = set()
        major_diag = set()
        minor_diag = set()

        # init setup
        res = []
        cur_board = [['.' for _ in range(n)] for _ in range(n)]

        backtrack(0, cur_board)

        return res
        
16900