52. N-Queens II
Asked at 9Bloomberg28Amazon27Microsoft25Google22Meta22Liftoff100Zenefits100Deutsche Bank62Snowflake39
Problem
Return the number of distinct ways to place n non-attacking queens on an n×n chessboard.
Example: n = 4 → 2; n = 1 → 1
Constraints: n ≤ 9.
Count placements only. Bitmasks for columns and both diagonals: free = ~(cols | d1 | d2) & full; take the lowest bit each time; shift the diagonals by one when moving to the next row.
Complexity: O(n!), very fast in practice.
class Solution:
def totalNQueens(self, n: int) -> int:
full = (1 << n) - 1
def bt(cols, d1, d2):
if cols == full:
return 1
count, free = 0, ~(cols | d1 | d2) & full
while free:
bit = free & -free
free -= bit
count += bt(cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1)
return count
return bt(0, 0, 0)
assert Solution().totalNQueens(4) == 2
assert Solution().totalNQueens(1) == 1
assert Solution().totalNQueens(8) == 92
class Solution {
private int full;
public int totalNQueens(int n) {
full = (1 << n) - 1;
return bt(0, 0, 0);
}
private int bt(int cols, int d1, int d2) {
if (cols == full) return 1;
int count = 0;
for (int free = ~(cols | d1 | d2) & full; free != 0; ) {
int bit = free & -free;
free -= bit;
count += bt(cols | bit, ((d1 | bit) << 1) & full, (d2 | bit) >> 1);
}
return count;
}
}
func totalNQueens(n int) int {
full := 1<<n - 1
var bt func(cols, d1, d2 int) int // bitmasks of attacked columns in the current row
bt = func(cols, d1, d2 int) int {
if cols == full {
return 1
}
count := 0
for free := ^(cols | d1 | d2) & full; free != 0; {
bit := free & -free // lowest free column
free -= bit
count += bt(cols|bit, (d1|bit)<<1&full, (d2|bit)>>1)
}
return count
}
return bt(0, 0, 0)
}