
									 Problem
								
								
									 Solution
								
								
									 Submissions
								
								
							N-Queens Problem with Backtracking
								Certification: Advanced Level
								Accuracy: 50%
								Submissions: 2
								Points: 15
							
							Write a C++ program to solve the N-Queens problem using backtracking. The N-Queens problem is to place N chess queens on an N×N chessboard so that no two queens attack each other. Queens can attack horizontally, vertically, and diagonally. The program should find and display one valid solution for placing N queens on the board.
Example 1
- Input: n = 4
- Output: 
 . Q . .
 . . . Q
 Q . . .
 . . Q .
- Explanation: - We need to place 4 queens on a 4×4 chessboard. 
- Starting from the first row, we place the first queen at position (0,1). 
- For the second row, we find a safe position at (1,3) that doesn't conflict with the first queen. 
- For the third row, we place the queen at (2,0) which is safe from previous queens. 
- Finally, we place the fourth queen at (3,2) completing a valid solution.
 
- We need to place 4 queens on a 4×4 chessboard. 
Example 2
- Input: n = 8
- Output: 
 Q . . . . . . .
 . . . . Q . . .
 . . . . . . . Q
 . . . . . Q . .
 . . Q . . . . .
 . . . . . . Q .
 . Q . . . . . .
 . . . Q . . . .
- Explanation: - We need to place 8 queens on an 8×8 chessboard. 
- Using backtracking, we systematically try placing queens in each row. 
- For each position, we check if it's safe from all previously placed queens. 
- If a position leads to no solution, we backtrack and try the next position. 
- The algorithm continues until all 8 queens are successfully placed without conflicts.
 
- We need to place 8 queens on an 8×8 chessboard. 
Constraints
- 1 ≤ n ≤ 15
- You must use backtracking algorithm
- Display the board with 'Q' for queens and '.' for empty spaces
- Find and display only one valid solution
- 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 a 2D vector or array to represent the chessboard
- Create a recursive function that tries to place queens row by row
- 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 (same row, column, or diagonal)
- If placing a queen leads to no solution, backtrack by removing it and trying the next position
- Use helper functions to check if a position is safe from attacks
- Once all N queens are placed successfully, display the solution
