Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Solve the N-Queens problem

Place N queens on an N×N board so that no two queens attack each other.

Python practice28 minRecursion & BacktrackingAdvancedLast updated March 27, 2026

Problem statement

Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' indicates a queen and '.' indicates an empty space. Represent each board as a list of n strings of length n. Return the list of solutions sorted lexicographically by the concatenation of their rows (so results are deterministic).

Task

Use backtracking to generate all distinct N-Queens solutions and return them in a consistent, sorted ordering.

Examples

n = 1

Input

1

Output

[['Q']]

Only one cell and one queen — the single solution is a board with 'Q'.

Input format

A single integer n.

Output format

A list of solutions. Each solution is a list of n strings representing the board. The outer list must be sorted for determinism.

Constraints

1 <= n <= 10. Solutions must not place any two queens in the same row, column, or diagonal.

Samples

Sample 1

Input

4

Output

[['..Q.', 'Q...', '...Q', '.Q..'], ['.Q..', '...Q', 'Q...', '..Q.']]

Two distinct 4x4 solutions. The returned list is sorted lexicographically.