N-Queens
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. Each arrangement is rendered as a list of n strings, one per row, using Q for a queen and . for an empty square.
n is between 1 and 9. Note that some sizes have no solutions at all (n = 2 and n = 3 return an empty list), and n = 9 has 352, so the algorithm must enumerate systematically rather than guess.
Examples
- Input:
- n = 4
- Output:
- [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
The two essentially mirrored solutions for a 4 × 4 board. In the first, queens sit at columns 1, 3, 0, 2 of rows 0-3; no pair shares a column or diagonal.
- Input:
- n = 1
- Output:
- [["Q"]]
A single queen on a 1 × 1 board attacks nothing.
Hints
One at a time — struggle first, peek second.
Your thinking space — verify on LeetCode, then mark it.