N-Queens II

Hard

Topics
Backtracking

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

.Q.....QQ.....Q.
One valid placement for n = 4: no two queens share a row, a column, or either diagonal. Since exactly one queen goes per row, the search only has to choose a column per row, and the diagonal test is |col difference| == |row difference|. The answer counts all such placements, not the board itself.
One of the valid boards; Q is a queen and . an empty square.
Input:  n = 4
Output: 2

Example 2

Q
Input:  n = 1
Output: 1

Example 3

Q...........Q..........Q.....Q....Q...........Q..Q.........Q....
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

  1. Recurse with (cols, d1, d2), starting all zero.
  2. Count a solution when cols == allMask, meaning every column is filled.
  3. Compute the available squares and loop over its set bits.
  4. 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..9

Complexity

  • 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 n array 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 == allMask says the same thing more cheaply.
  • Using avail &= avail - 1 to clear the lowest bit but still needing p. Both idioms are fine; mixing them loses track of which square was chosen.
  • Assuming the bitmask version needs n <= 64 to be stated. It does in a fixed-width language, and at n <= 9 it 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.count
Asked at Deutsche Bank
SensAI
Beta
Tap the mic to stop voice mode