N Queens
Given an integer n, place n queens on an n × n chessboard so that no two queens attack each other.
A queen can attack another queen if they are in the same:
- Row
- Column
- Diagonal
Return all distinct solutions.
Each solution should be represented as a list of strings, where:
- Q represents a queen.
- . represents an empty cell.
Example 1
Input
n = 4
Output
2
Explanation
There are two distinct ways to place four queens so that no two queens attack each other.
The two solutions are:
. Q . .
. . . Q
Q . . .
. . Q .
and
. . Q .
Q . . .
. . . Q
. Q . .
Therefore:
Number of solutions = 2
Example 2
Input
n = 1
Output
1
Explanation
A single queen can be placed on the only available cell.
Q
Therefore:
Number of solutions = 1
Constraints
Hints:
Hint 1
Place queens one row at a time.
For each row, try placing a queen in every column.
Hint 2
Before placing a queen at (row, col), check whether:
- The column already contains a queen.
- The main diagonal already contains a queen.
- The anti-diagonal already contains a queen.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 25, 2026
Last updated
Aug 26, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output