Every Way to Place N Non-Attacking Queens on a Board

Implement nonAttackingQueenBoards

Place n chess queens on an n×n board so that no two attack each other — no shared row, column, or diagonal — and return every distinct arrangement that achieves this. Since two queens on the same row always attack each other, placing exactly one queen per row and choosing its column is enough to describe any candidate arrangement. Checking whether a candidate column is safe by re-examining every queen placed in an earlier row works, but repeats that examination from scratch at every single column tried, at every row. Maintaining directly which columns and which diagonals are currently occupied turns that repeated re-derivation into a single lookup — the search explores the exact same tree either way, but each conflict check along the way is answered immediately instead of recomputed.

Example 1:

Input: n = 4

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

Example 2:

Input: n = 1

Output: [["Q"]]

Example 3:

Input: n = 2

Output: []

+ 2 hidden test cases run on Submit.

Constraints:

  • 1 ≤ n ≤ 8
  • A queen attacks any square sharing its row, column, or either diagonal
  • Each board is returned as n strings of length n, using 'Q' for a queen and '.' for an empty square
  • Results are returned sorted (each board compared row by row) for a stable, checkable answer

n =

4