
Problem
Solution
Submissions
Solve the N-Queens Problem
Certification: Advanced Level
Accuracy: 100%
Submissions: 10
Points: 15
Write a Python function that solves the N-Queens problem. The N-Queens problem is placing N chess queens on an N×N chessboard so that no two queens threaten each other. Thus, a solution requires that no two queens share the same row, column, or diagonal.
Example 1
- Input: n = 4
- Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
- Explanation:
- Step 1: Create a 4×4 chessboard.
- Step 2: Find all possible arrangements of 4 queens where none threaten each other.
- Step 3: There are two valid solutions:
- Solution 1:
.Q..
...Q
Q...
..Q. - Solution 2:
..Q.
Q...
...Q
.Q.. - Step 4: Return both solutions as shown in the output format.
Example 2
- Input: n = 1
- Output: [["Q"]]
- Explanation:
- Step 1: Create a 1×1 chessboard.
- Step 2: Place 1 queen on the board.
- Step 3: There is only one possible arrangement: a single queen on the only square.
- Step 4: Return the solution as [["Q"]].
Constraints
- 1 ≤ n ≤ 9
- Time Complexity: O(N!), where N is the number of queens
- Space Complexity: O(N²)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use backtracking to place queens row by row
- Check if a position is safe by verifying no queen threatens it
- Use sets to keep track of occupied columns and diagonals
- For each valid solution, construct the board representation