Problem description

On an n by n chessboard you must place n queens so that no two of them threaten each other. A queen attacks any piece sharing its row, its column, or either of its two diagonals, so a valid arrangement keeps every pair of queens off the same row, column, and diagonal.

Return all distinct board layouts that satisfy this rule. Represent each board as a list of strings where the character 'Q' marks a queen and '.' marks an empty square.

Example 1

Input: n = 4

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

There are exactly two ways to place four non-attacking queens on a four by four board.

Example 2

Input: n = 1

Output: [["Q"]]

A single queen on a one by one board trivially satisfies the rule.

Constraints

  • 1 <= n <= 9
  • Exactly one queen is placed in each row and each column
  • No two queens may share a diagonal

After the pattern

Now solve one you haven't seen.

Beacon Ridge Layouts is our own problem on the technique behind N-Queens: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free