N-Queens

Backtracking, problem 7 of 7

N-Queens

Hard

LC #51

constraint satisfactionpruning

Not attempted yet

Place n chess queens on an n × n board so that no two queens share a row, a column or a diagonal. Return every such arrangement, in any order.

Describe each board as a list of n strings, one per row, using "Q" for a queen and "." for an empty square.

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: []

Two queens on a 2 × 2 board always attack each other.

Constraints

  • 1 ≤ n ≤ 9

Python

Loading draft…

Test results

7 tests available

No results yet

Run tests your code against the examples; Submit runs the hidden tests too.

3 examples, 4 hidden

Run examples, then submit all tests.