N-Queens II

Count the n-queens solutions using bitmask backtracking over columns, diagonals, and anti-diagonals.

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

Problem#

Return the number of distinct ways to place n queens on an n × n board such that no two attack each other.

Examples#

  • n = 42
  • n = 11

Constraints#

  • 1 <= n <= 9.

Approach#

Bitmask backtracking. Three bitmasks track occupied columns, anti-diagonals (/), and diagonals (\). At each row, available positions = ~(cols | diag | anti) & ((1<<n) - 1). Pick the lowest set bit, recurse, clear.

Solution#

N-Queens II
class Solution {
public:
int totalNQueens(int n) {
int count = 0;
function<void(int,int,int,int)> dfs = [&](int row, int cols, int diag, int anti) {
if (row == n) { ++count; return; }
int avail = ~(cols | diag | anti) & ((1 << n) - 1);
while (avail) {
int bit = avail & -avail; // lowest set bit
avail ^= bit;
dfs(row + 1, cols | bit, (diag | bit) << 1, (anti | bit) >> 1);
}
};
dfs(0, 0, 0, 0);
return count;
}
};

Editorial#

Shifting the diagonal/anti-diagonal masks on recursion accounts for their diagonal progression — \ moves right-and-down (shift left), / moves left-and-down (shift right). The lowest-set-bit bit & -bit trick iterates exactly the available columns, skipping blocked ones.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.