
Problem
Solution
Submissions
N-Queens Problem
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C# program to implement the SolveNQueens(int n) function that returns all distinct solutions to the N-Queens puzzle. Each solution contains a distinct board configuration of placing N queens on an N×N chessboard such that no two queens threaten each other. This means no two queens can share the same row, column, or diagonal.
Example 1
- Input: n = 4
- Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
- Explanation:
- There are two distinct solutions to the 4-queens puzzle as shown in the output.
Example 2
- Input: n = 1
- Output: [["Q"]]
- Explanation:
- There is exactly one solution when n = 1.
Constraints
- 1 <= n <= 9
- Each solution must be represented as a board configuration where 'Q' indicates a queen and '.' indicates an empty space
- Time Complexity: O(n!)
- Space Complexity: O(n^2)
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 with a recursive approach
- Keep track of which columns, diagonals, and anti-diagonals are occupied
- A diagonal can be represented by (row - col), and an anti-diagonal by (row + col)
- Place queens one row at a time and check for conflicts
- Build the board representation once a valid solution is found