iq.lab
Python starts when a code cell comes near or you run one
hardBacktracking target 40 min

Place n queens

A queen on a chessboard attacks every square in its row, in its column, and along both of its diagonals, however far away. You get a whole number n. Return every way to place n queens on an n by n board so that no queen attacks another.

Write each placement as a list of n strings, one per row from top to bottom. Each string has n characters: "Q" for a square with a queen and "." for an empty square.

Return each placement once, in any order. If there is no placement, return an empty list.

Example 1
Inputn = 4Output[[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]

Counting columns from 0, the first placement has its queens in columns 1, 3, 0, 2 from the top row down. The second is its mirror image: 2, 0, 3, 1.

Example 2
Inputn = 1Output[["Q"]]

One queen on one square has nothing to attack.

Example 3
Inputn = 3Output[]

Wherever the top queen stands, the middle row has at most one safe square, and a queen there leaves the bottom row with none.

Constraints
  • 1 ≤ n ≤ 9

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.