N-Queens
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 to the n-queens puzzle.
Example 1
|col difference| == |row difference|. The answer lists every such board.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
Place one queen per row, which removes row conflicts by construction. What remains is to avoid repeating a column or either diagonal, and the whole art is encoding those three constraints so each test is O(1).
Columns index directly. For diagonals, notice that row - col is constant along one direction and row + col along the other — so two arrays indexed by those sums mark occupancy. row - col can be negative, so it is shifted by n to become a valid index.
The bitmask variant packs all three into integers and is the version to reach for under pressure: available = ~(cols | diag1 | diag2) & allMask, then pick the lowest set bit with avail & -avail. Shifting the diagonal masks by one per row is what propagates them.
Approach
- Recurse by row, counting a solution when every row is filled.
- For each column, skip it if the column or either diagonal lane is occupied.
- Mark all three, recurse to the next row, then unmark.
- Return the count.
Dry Run
n = 4 -- the two solutions, with the column chosen per row
columns [1, 3, 0, 2] columns [2, 0, 3, 1]
. Q . . . . Q .
. . . Q Q . . .
Q . . . . . . Q
. . Q . . Q . .
answer 2
diagonal indexing for the queen at row 1, column 3
row - col = -2, shifted by n = 4 -> index 2
row + col = 4 -> index 4
known counts
n 1 2 3 4 5 6 7 8 9
count 1 0 0 2 10 4 40 92 352Complexity
- Time — O(n!) as a loose bound: row 0 has
nchoices, row 1 at mostn-1, and so on, with the diagonal pruning cutting far more in practice. At the stated bound of 9 the whole search is a few thousand nodes. - Space — O(n) for the recursion depth and the three occupancy arrays. The bitmask version is O(n) stack and three integers.
Common Pitfalls
- Scanning the board to validate each placement, which is O(n) per test and O(n) deeper per row. The three occupancy structures make it O(1).
- Forgetting to shift
row - colinto non-negative range, which indexes an array from the wrong end — in Python it silently wraps and produces wrong answers rather than crashing. - Using one diagonal array for both directions. They are independent constraints and need separate marks.
- Failing to unmark on the way out of the recursion, which leaks occupancy into sibling branches.
- In the bitmask version, shifting the diagonal masks in the wrong direction, or forgetting to mask with
allMaskso bits drift above positionn. - Assuming
n = 2andn = 3have solutions. They have none, and a solver that returns 1 for them is almost certainly counting the empty placement.
Full Solution — all languages
class Solution:
def solveNQueens(self, n):
self.total = 0
cols = [False] * n
diag = [False] * (2 * n)
anti = [False] * (2 * n)
def place(row):
if row == n:
self.total += 1
return
for c in range(n):
if cols[c] or diag[row - c + n] or anti[row + c]:
continue
cols[c] = diag[row - c + n] = anti[row + c] = True
place(row + 1)
cols[c] = diag[row - c + n] = anti[row + c] = False
place(0)
return self.totalimport java.util.*;
class Solution {
public int solveNQueens(int n) {
size = n;
total = 0;
cols = new boolean[n];
diag = new boolean[2 * n];
anti = new boolean[2 * n];
place(0);
return total;
}
private int size, total;
private boolean[] cols, diag, anti;
private void place(int row) {
if (row == size) {
total++;
return;
}
for (int c = 0; c < size; c++) {
if (cols[c] || diag[row - c + size] || anti[row + c]) continue;
cols[c] = diag[row - c + size] = anti[row + c] = true;
place(row + 1);
cols[c] = diag[row - c + size] = anti[row + c] = false;
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int solveNQueens(int n) {
int total = 0;
vector<char> cols(n, 0), diag(2 * n, 0), anti(2 * n, 0);
function<void(int)> place = [&](int row) {
if (row == n) {
total++;
return;
}
for (int c = 0; c < n; c++) {
if (cols[c] || diag[row - c + n] || anti[row + c]) continue;
cols[c] = diag[row - c + n] = anti[row + c] = 1;
place(row + 1);
cols[c] = diag[row - c + n] = anti[row + c] = 0;
}
};
place(0);
return total;
}
};/**
* @param {number} n
* @return {number}
*/ var solveNQueens = function(n) {
let total = 0;
const cols = new Array(n).fill(false);
const diag = new Array(2 * n).fill(false);
const anti = new Array(2 * n).fill(false);
const place = (row) => {
if (row === n) {
total++;
return;
}
for (let c = 0; c < n; c++) {
if (cols[c] || diag[row - c + n] || anti[row + c]) continue;
cols[c] = diag[row - c + n] = anti[row + c] = true;
place(row + 1);
cols[c] = diag[row - c + n] = anti[row + c] = false;
}
};
place(0);
return total;
};