N-Queens

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 to the n-queens puzzle.

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 lists every such board.
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

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

  1. Recurse by row, counting a solution when every row is filled.
  2. For each column, skip it if the column or either diagonal lane is occupied.
  3. Mark all three, recurse to the next row, then unmark.
  4. 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  352

Complexity

  • Time — O(n!) as a loose bound: row 0 has n choices, row 1 at most n-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 - col into 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 allMask so bits drift above position n.
  • Assuming n = 2 and n = 3 have 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.total
Asked at TikTok
SensAI
Beta
Tap the mic to stop voice mode