← Back to Algorithms, page 3

algorithms-0049 · Hard senior

N-Queens: place n queens on an n x n board so that no two attack each other, and return every valid board.

Place one queen per row. For each column in the current row, skip it if the column, the diagonal (r - c) or the anti-diagonal (r + c) is already used; otherwise place the queen, recurse to the next row and remove it afterwards. Sets make each conflict check O(1). The search is exponential but pruning keeps it fast for small n.

Full answer

Problem

Return all distinct placements of n queens on an n x n board with no two queens sharing a row, column or diagonal. Each board is a list of strings, with "Q" for a queen and "." for an empty square.

Example: n = 4 has 2 solutions: [".Q..", "...Q", "Q...", "..Q."] and ["..Q.", "Q...", "...Q", ".Q.."].

Constraints: 1 <= n <= 9. Solution counts for n = 1 to 8 are 1, 0, 0, 2, 10, 4, 40, 92.

Brute force

Try every choice of n squares out of n^2: C(64, 8), about 4.4 x 10^9 for n = 8. One queen per row reduces it to n^n (about 1.7 x 10^7), and one per column to n! (40320), still checking every full board.

Optimal approach

place(r):

  1. If r == n, record the board.
  2. For each column c: skip if c is in cols, r - c in diag or r + c in anti.
  3. Otherwise add c, r - c, r + c to the sets, record the column, recurse with r + 1, then remove them.

Why it works

Each row must hold exactly one queen, so building row by row covers every valid board. Two queens share a diagonal exactly when r - c is equal (top-left to bottom-right) and an anti-diagonal when r + c is equal. Checking these sets rejects a conflicting square immediately, which prunes whole subtrees early rather than discovering the conflict on a complete board. Undoing the choices restores the state for the next column.

Complexity

Time is exponential: bounded by O(n!) placements, and much less in practice because of pruning, with O(n^2) to build each output board. Space O(n) for the sets and recursion, plus the output.

Code

python
def solve_n_queens(n):
    """All boards with n non-attacking queens. Backtracking with O(1) conflict checks."""
    cols, diag, anti = set(), set(), set()    # used column, r - c, r + c
    queens = []                               # queens[r] = column of the queen in row r
    boards = []

    def place(r):
        if r == n:
            boards.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
            return
        for c in range(n):
            if c in cols or (r - c) in diag or (r + c) in anti:
                continue                      # attacked: prune this branch
            cols.add(c)
            diag.add(r - c)
            anti.add(r + c)
            queens.append(c)
            place(r + 1)
            cols.remove(c)
            diag.remove(r - c)
            anti.remove(r + c)
            queens.pop()

    place(0)
    return boards


if __name__ == "__main__":
    assert solve_n_queens(4) == [[".Q..", "...Q", "Q...", "..Q."],
                                 ["..Q.", "Q...", "...Q", ".Q.."]]
    assert solve_n_queens(1) == [["Q"]]
    assert solve_n_queens(2) == [] and solve_n_queens(3) == []
    assert [len(solve_n_queens(n)) for n in range(1, 9)] == [1, 0, 0, 2, 10, 4, 40, 92]
    print("all tests passed")

Save as a49_n_queens.py and run python3 a49_n_queens.py. It prints all tests passed (Python 3.13.5).

Edge cases

n = 1 has one board. n = 2 and n = 3 have none. The test checks counts up to 8. For counting only, skip building strings; bitmasks for columns and diagonals make it faster still. Symmetry (mirror the first-row choices) halves the work for counting.

Pattern

Backtracking for constraint satisfaction with O(1) feasibility checks. The same structure solves Sudoku, graph colouring, word search on a grid and placing items under constraints.

python
def solve_n_queens(n):
    """All boards with n non-attacking queens. Backtracking with O(1) conflict checks."""
    cols, diag, anti = set(), set(), set()    # used column, r - c, r + c
    queens = []                               # queens[r] = column of the queen in row r
    boards = []

    def place(r):
        if r == n:
            boards.append(["." * c + "Q" + "." * (n - c - 1) for c in queens])
            return
        for c in range(n):
            if c in cols or (r - c) in diag or (r + c) in anti:
                continue                      # attacked: prune this branch
            cols.add(c)
            diag.add(r - c)
            anti.add(r + c)
            queens.append(c)
            place(r + 1)
            cols.remove(c)
            diag.remove(r - c)
            anti.remove(r + c)
            queens.pop()

    place(0)
    return boards


if __name__ == "__main__":
    assert solve_n_queens(4) == [[".Q..", "...Q", "Q...", "..Q."],
                                 ["..Q.", "Q...", "...Q", ".Q.."]]
    assert solve_n_queens(1) == [["Q"]]
    assert solve_n_queens(2) == [] and solve_n_queens(3) == []
    assert [len(solve_n_queens(n)) for n in range(1, 9)] == [1, 0, 0, 2, 10, 4, 40, 92]
    print("all tests passed")

Row-by-row backtracking with sets for columns, diagonals (r - c) and anti-diagonals (r + c); checks solution counts for n = 1 to 8.

Complexity

Time: Exponential; bounded by O(n!) placements, much less with pruning. Space: O(n) plus output. Bitmask versions are faster for counting solutions only.

By level

Fresher: Places queens row by row with a safety check and backtracks, tracing n = 4. Should test n = 2 and n = 3.

Mid: Uses O(1) set checks with r - c and r + c and explains pruning. Explains why one queen per row loses no solutions.

Senior: Uses bitmasks and symmetry for counting, discusses constraint propagation and compares with general CSP solvers. Explains how symmetry halves the work.

Key points

  • One queen per row
  • Diagonal key r - c, anti-diagonal key r + c
  • Sets give O(1) conflict checks
  • Undo every choice after recursion
  • Pruning cuts subtrees early

Common mistakes

  • Checking conflicts by scanning the whole board each time
  • Mixing up r - c and r + c
  • Forgetting to remove the queen when backtracking
  • Returning only one solution when all are asked

Follow-ups

  • How would you only count solutions faster?
  • How would you solve Sudoku with the same approach?
  • How can symmetry reduce the work?

Tips

  • Explain the diagonal keys with a small drawing
  • State why one queen per row is safe
  • Test n = 2 and n = 3

Evaluation rubric

  • Correct backtracking and pruning
  • Correct diagonal checks
  • Correct output format
  • Reasonable complexity discussion