Skip to content
Problem 51 · LeetCode 51(opens in a new tab)

N-Queens

HardBacktracking

A queen in chess attacks every square in its row, its column and both of its diagonals. You are given a board size n, and you must put n queens on an n × n board so that no queen attacks another.

Return every such placement. Write each board as n strings, one per row, with 'Q' for a queen and '.' for an empty square. The boards can come back in any order.

Example 1

Input:  n = 6
Output: [[".Q....", "...Q..", ".....Q", "Q.....", "..Q...", "....Q."],  ← board 1
         ["..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.."],  ← board 2
         ["...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..."],  ← board 3
         ["....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...."]]  ← board 4
Why:    exactly four ways keep every queen safe
2 more examples and the constraints

Example 2

Input:  n = 3
Output: []
Why:    whatever you try, the middle-row queen is attacked

Example 3

Input:  n = 2
Output: []
Why:    two queens on a 2 × 2 board always share a line

Constraints

  • 1 ≤ n ≤ 9

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Every column orderO(n!·n²)
  2. Backtracking with attack setsO(n!)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for n = 9Verdict
Every column orderO(n!·n²)
Correct, but builds every board
Backtracking with attack setsO(n!)
Best; prunes as it places

n = the board size. Backtracking visits only partial boards that are still safe, far fewer than n!.

Edge cases to test

  • n = 1. One queen on one square is a valid board: return [["Q"]].
  • n = 2 and n = 3. No board works, so return an empty list, not a list holding an empty board.
  • Diagonal keys. r − c can be negative. A set handles that; an array needs an offset such as + n.
  • Largest n. n = 9 has 352 boards. The answer itself is the biggest thing in memory.

Common mistakes

  • Checking only one diagonal direction. Both r − c and r + c must be free.
  • Forgetting to remove the queen from the sets after the recursive call, so later rows see ghosts.
  • Saving the shared queens list itself instead of a fresh board, so every saved board changes as the search goes on.

How to talk through it

  1. 1Clarify. Do you want every board or just a count? Any order? What format for a board?
  2. 2Shrink the search. One queen per row and per column, so a board is a column order: n! options, not n² choose n.
  3. 3Prune early. Check each queen as it is placed. Name the three sets: columns, r − c and r + c.
  4. 4Code the backtracking. Place, recurse, undo. Say out loud where the undo happens.
  5. 5Test out loud. n = 1 gives one board, n = 2 and n = 3 give none, n = 4 gives two.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?