<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 {
public:
    unordered_set<int> validQueenPoss(int n, int row, const vector<int>& queenPoss) {
        unordered_set<int> validPoss;
        for(int i = 0; i < n; i++) {
            validPoss.insert(i);
        }

        for(int i = 0; i < row; i++) {
            int queenPos = queenPoss[i];
            validPoss.erase(queenPos);

            int yDiff = row - i;
            int x1 = queenPos + yDiff;
            int x2 = queenPos - yDiff;
            validPoss.erase(x1);
            validPoss.erase(x2);
        }

        return std::move(validPoss);
    }

    vector<vector<int>> solveNQueens(int n, int row, vector<int>& queenPoss) {
        if (row == n)
            return {queenPoss};
        
        auto validPoss = validQueenPoss(n, row, queenPoss);

        vector<vector<int>> validBoards;

        for(int pos : validPoss) {
            queenPoss[row] = pos;
            auto boards = solveNQueens(n, row+1, queenPoss);
            validBoards.insert(validBoards.end(), make_move_iterator(boards.begin()), make_move_iterator(boards.end()));
        }

        return std::move(validBoards);
    }

    vector<vector<string>> solveNQueens(int n) {
        vector<int> queenPoss(n);
        auto boards = solveNQueens(n, 0, queenPoss);

        vector<vector<string>> strBoards(boards.size(), vector<string>(n, string(n, '.')));
        for(int i = 0; i < boards.size(); i++) {
            auto& board = boards[i];
            for(int row = 0; row < n; row++) {
                int col = board[row];
                strBoards[i][row][col] = 'Q';
            }
        }

        return std::move(strBoards);
    }
};
18971