noodleProblems/
N-Queens
#59

N-Queens

AlgorithmhardArrayBacktracking

The **n-queens** puzzle places n queens on an n x n chessboard so that no two queens attack each other — no two share a row, column, or diagonal.

Given an integer n, return **all distinct** solutions. Each solution is a board drawn as an array of n strings, where 'Q' marks a queen and '.' marks an empty square. Solutions may be returned in any order, and the rows within each board run top to bottom.

Example cases

  • n = 4
    in n = 4
    out [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
    There are exactly two distinct ways to place four non-attacking queens on a 4×4 board.
  • n = 1
    in n = 1
    out [["Q"]]
    A single queen on a 1×1 board.
  • n = 2 (none)
    in n = 2
    out []
    No placement avoids mutual attack on a 2×2 board.

Constraints

  • 1 <= n <= 9
Saved
n =
4