Skip to content

N-Queens

Place n queens on an n by n board so that none attack each other, one row at a time with backtracking.

HardBacktracking
Solve on LeetCode

The problem

You get an integer n. Place n queens on an n by n chessboard so that no two of them share a row, a column or a diagonal, and return every such arrangement. Each board is a list of n strings, one per row, with Q for a queen and . for an empty square; the boards can be in any order.

Input n = 6

Output [[".Q....", "...Q..", ".....Q", "Q.....", "..Q...", "....Q."], ["..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.."], ["...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..."], ["....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...."]]

A 6 by 6 board has exactly 4 safe arrangements.

Input n = 3

Output []

There is no way to place three queens on a 3 by 3 board without two of them attacking each other.

Key constraint: n is at most 9. Every row must hold exactly one queen, so the search only has to choose a column for each row.

How to spot the pattern

  • You must list every arrangement that satisfies a set of constraints.
  • Choices are made one row at a time, and an early clash makes the rest of that branch pointless.

The idea

Each row gets exactly one queen, so go row by row and choose a column for each. A square is safe when no earlier queen uses its column or either of its diagonals. Every square on one diagonal has the same row - col, and every square on the other has the same row + col, so three boolean arrays answer the safety question in O(1); place the queen, solve the next row, then remove it and try the next column.

Brute force: Try every way to place n queens on the n^2 squares and test each placement, which is about C(n^2, n) boards, far too many even for n = 8.

Step by step

  1. 1Keep boolean arrays for used columns, used row - col diagonals and used row + col diagonals.
  2. 2Write backtrack(row); when row == n, turn the chosen columns into board strings and save them.
  3. 3For each column c in this row, skip it if its column or either diagonal is already taken.
  4. 4Otherwise mark all three, record c for this row and call backtrack(row + 1).
  5. 5Unmark all three afterwards, so the next column starts from a clean state.

See the pattern move

The backtracking pattern on a small example. Step through it, or press play.

Code

class Solution:
    def solveNQueens(self, n: int) -> List[List[str]]:
        result = []
        queen_col = [0] * n                # queen_col[r] is the column of the queen in row r
        col_used = [False] * n
        diag_used = [False] * (2 * n - 1)  # squares on one diagonal share row - col
        anti_used = [False] * (2 * n - 1)  # squares on the other share row + col

        def backtrack(row: int) -> None:
            if row == n:
                result.append(["." * c + "Q" + "." * (n - c - 1) for c in queen_col])
                return
            for c in range(n):
                d, a = row - c + n - 1, row + c
                if col_used[c] or diag_used[d] or anti_used[a]:
                    continue  # attacked by a queen in an earlier row
                col_used[c] = diag_used[d] = anti_used[a] = True
                queen_col[row] = c
                backtrack(row + 1)
                col_used[c] = diag_used[d] = anti_used[a] = False

        backtrack(0)
        return result

Complexity

Time

O(n!)

Space

O(n)

Row r has at most n - r safe columns left, so the search is bounded by n! and pruning cuts it much further; writing out each saved board adds O(n^2).

Watch out for

  • Checking columns and only one of the two diagonal directions.
  • Using row - col directly as an array index when it can be negative; add n - 1 first.
  • Not undoing the marks after the recursive call, so later rows see queens that were removed.

Follow-up questions

What if you only need the number of solutions?

Run the same search and count instead of building boards. That is N-Queens II.

Can you make the safety check even faster?

Store the taken columns and diagonals as bits of three integers. The free squares in a row are then the zero bits of cols | diag | anti, and you can pick them off one at a time with bit tricks.

In Hinglish

Har row mein ek hi queen aayegi, toh row by row column chuno. Column, row - col aur row + col teeno free hon tabhi queen rakho, aage badho, aur wapas aakar hata do.

Related problems