N-Queens

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the solutions in any order.

Each solution contains a distinct board configuration, represented as a list of n strings where:

  • Q indicates a queen.
  • . indicates an empty square.

No two queens in a valid board may share the same row, column, or diagonal.

Example 1
Inputn = 4
Output[[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
There are exactly two distinct ways to place 4 queens so that none attack each other.
Example 2
Inputn = 1
Output[["Q"]]
A single queen can be placed on the only square of a 1 x 1 board.

Constraints

  • 1 <= n <= 9

Asked at 16 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate