
Problem
Solution
Submissions
N-Queens Problem
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to solve the N-Queens puzzle. The N-Queens puzzle is the problem of placing N chess queens on an N×N chessboard so that no two queens attack each other. Queens can attack horizontally, vertically, and diagonally. Return all distinct solutions to the N-Queens puzzle.
Example 1
- Input: n = 4
- Output: 2 solutions
- Explanation:
- For a 4x4 board, there are exactly 2 distinct solutions.
- Solution 1: Queens at positions (0,1), (1,3), (2,0), (3,2).
- Solution 2: Queens at positions (0,2), (1,0), (2,3), (3,1).
- For a 4x4 board, there are exactly 2 distinct solutions.
Example 2
- Input: n = 1
- Output: 1 solution
- Explanation:
- For a 1x1 board, there is exactly 1 solution.
- The single queen is placed at position (0,0).
- No conflicts possible with only one queen.
- For a 1x1 board, there is exactly 1 solution.
Constraints
- 1 <= n <= 9
- Each solution contains distinct board configurations
- Queens cannot attack each other horizontally, vertically, or diagonally
- Time Complexity: O(N!)
- 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 algorithm to explore all possible placements
- For each row, try placing a queen in each column and check if it's safe
- A position is safe if no other queen can attack it (check column, diagonal, and anti-diagonal)
- Use arrays to keep track of occupied columns and diagonals for efficient conflict checking
- When a valid solution is found, store it and backtrack to find more solutions
- Recursively solve for each row until all N queens are placed