N-Queens

Return all distinct n-queens placements as board strings — bitmask backtracking with board reconstruction.

Hard
Time O(n!) Space O(n)
LeetCode
5 min read
backtracking bitmask

Problem#

Place n queens on an n × n board so none attack each other. Return all distinct configurations as a list of board strings.

Examples#

  • n = 4[[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]

Constraints#

  • 1 <= n <= 9.

Approach#

Bitmask DFS (same as N-Queens II) but record the column choice per row, then build the board strings at the leaf.

Solution#

N-Queens
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> out;
vector<int> placement(n, 0);
function<void(int,int,int,int)> dfs = [&](int row, int cols, int diag, int anti) {
if (row == n) {
vector<string> board(n, string(n, '.'));
for (int r = 0; r < n; ++r) board[r][placement[r]] = 'Q';
out.push_back(board);
return;
}
int avail = ~(cols | diag | anti) & ((1 << n) - 1);
while (avail) {
int bit = avail & -avail;
avail ^= bit;
placement[row] = __builtin_ctz(bit);
dfs(row + 1, cols | bit, (diag | bit) << 1, (anti | bit) >> 1);
}
};
dfs(0, 0, 0, 0);
return out;
}
};

Editorial#

Same DFS structure as N-Queens II; the additional cost is rendering the board on each accepted leaf. __builtin_ctz returns the column index (0-based) from the bitmask.

Complexity#

  • Time: O(n!).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.