N-Queens II
Hard
Topics
The n-queens puzzle places n queens on an n x n chessboard so that no two queens attack each other (no shared row, column, or diagonal). Given an integer n, return the number of distinct solutions.
Example 1
|col difference| == |row difference|. The answer counts all such placements, not the board itself.Q is a queen and . an empty square.Input: n = 4 Output: 2
Example 2
Input: n = 1 Output: 1
Example 3
Input: n = 8 Output: 92
Constraints
- 1 <= n <= 9
Editorial — intuition, approach, complexity and pitfalls
Intuition
Same puzzle as n-queens, counted the same way, but written with bitmasks — which is the formulation worth knowing because it is both shorter and markedly faster.
Three integers carry the state: cols marks occupied columns, d1 the descending diagonals and d2 the ascending ones. The free squares in the current row are available = allMask & ~(cols | d1 | d2), and iterating them is p = avail & -avail to isolate the lowest set bit, then avail -= p.
The elegance is in the recursion step. Moving to the next row shifts the diagonal masks by one position — (d1 | p) << 1 and (d2 | p) >> 1 — because a diagonal threat moves one column sideways per row. No index arithmetic, no array bookkeeping, and the shift naturally discards threats that have left the board.
Approach
- Recurse with
(cols, d1, d2), starting all zero. - Count a solution when
cols == allMask, meaning every column is filled. - Compute the available squares and loop over its set bits.
- Recurse with the bit added to all three masks, shifting the diagonals by one.
Dry Run
n = 4, allMask = 0b1111
row 0, cols = 0b0000, d1 = 0, d2 = 0
available = 0b1111, so all four columns are free
take column 1 (bit 0b0010)
recurse with cols = 0b0010, d1 = 0b0100, d2 = 0b0001
row 1, available = 0b1111 & ~(0b0010 | 0b0100 | 0b0001) = 0b1000
only column 3 is free
... and so on
answer 2 matching the array-based version exactly for every n in 1..9Complexity
- Time — O(n!) with the same pruning as the array version, but a much smaller constant: the availability set is computed with three bitwise operations instead of
narray lookups. - Space — O(n) for the recursion depth. The state itself is three machine words, so there is no auxiliary array at all.
Common Pitfalls
- Shifting the diagonal masks in the same direction. The two diagonals travel opposite ways as the row advances, so one shifts left and the other right.
- Forgetting
allMask &before complementing. Without it,~produces an unbounded run of high bits — in Python an arbitrarily large negative integer — and the loop never terminates sensibly. - Shifting before adding the new queen's bit. The bit belongs in the mask for the current row, then the whole mask shifts.
- Testing completion by row depth and forgetting that
cols == allMasksays the same thing more cheaply. - Using
avail &= avail - 1to clear the lowest bit but still needingp. Both idioms are fine; mixing them loses track of which square was chosen. - Assuming the bitmask version needs
n <= 64to be stated. It does in a fixed-width language, and atn <= 9it is moot — but say so rather than leaving it implicit.
Full Solution — all languages
class Solution:
def totalNQueens(self, n):
all_mask = (1 << n) - 1
self.count = 0
def solve(cols, d1, d2):
if cols == all_mask:
self.count += 1
return
avail = all_mask & ~(cols | d1 | d2)
while avail:
p = avail & (-avail)
avail -= p
solve(cols | p, (d1 | p) << 1, (d2 | p) >> 1)
solve(0, 0, 0)
return self.countimport java.util.*;
class Solution {
public int totalNQueens(int n) {
count = 0;
all = (1 << n) - 1;
solve(0, 0, 0);
return count;
}
int count, all;
private void solve(int cols, int d1, int d2) {
if (cols == all) {
count++;
return;
}
int avail = all & ~(cols | d1 | d2);
while (avail != 0) {
int p = avail & (-avail);
avail -= p;
solve(cols | p, (d1 | p) << 1, (d2 | p) >> 1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int totalNQueens(int n) {
int all = (1 << n) - 1;
int count = 0;
function<void(int,int,int)> solve = [&](int cols, int d1, int d2) {
if (cols == all) {
count++;
return;
}
int avail = all & ~(cols | d1 | d2);
while (avail) {
int p = avail & (-avail);
avail -= p;
solve(cols | p, (d1 | p) << 1, (d2 | p) >> 1);
}
};
solve(0, 0, 0);
return count;
}
};/**
* @param {number} n
* @return {number}
*/ var totalNQueens = function(n) {
const all = (1 << n) - 1;
let count = 0;
const solve = (cols, d1, d2) => {
if (cols === all) {
count++;
return;
}
let avail = all & ~(cols | d1 | d2);
while (avail) {
const p = avail & (-avail);
avail -= p;
solve(cols | p, (d1 | p) << 1, (d2 | p) >> 1);
}
};
solve(0, 0, 0);
return count;
};