N-Queens

50 min · solveNQueens()

One queen controls an entire row, column, and both diagonals. Placing n of them without overlap turns a small board into a sharp search problem.

For an integer n, arrange n queens on an n × n board so no pair can attack each other. Return every distinct arrangement. Represent one arrangement as n row strings from top to bottom:

  • Q marks a queen.
  • . marks an empty square.

The arrangements may come back in any order, but the rows inside each arrangement must stay in top-to-bottom order. Some sizes have no solution; return [] for those sizes.

Constraints

  • 1 <= n <= 9
  • Every returned board has exactly n rows and one queen in each row.
  • No input produces more than 352 boards.

Hints

Rows and columns first

Place exactly one queen in each row. If you also forbid reused columns, row and column attacks disappear automatically.

Name each diagonal

Squares on one diagonal share row - column; squares on the other share row + column. Two sets can tell whether either diagonal is occupied.

Choose, record, undo

For the current row, try each safe column. Record its column and two diagonal keys, search the next row, then remove all three records before trying the next column.

Follow-up

Mirror-image boards arrive in pairs. Could symmetry reduce the search while still returning every distinct board?

Visible cases

Examples

Example 1

ready
Input
n = 4
Expected
[
  [
    ".Q..",
    "...Q",
    "Q...",
    "..Q."
  ],
  [
    "..Q.",
    "Q...",
    "...Q",
    ".Q.."
  ]
]
Why
four queens have exactly two non-attacking arrangements

Example 2

ready
Input
n = 1
Expected
[
  [
    "Q"
  ]
]
Why
the lone square holds the lone queen

Example 3

ready
Input
n = 2
Expected
[]
Why
every placement of two queens creates an attack

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite