Tutorialspoint
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)
RecursionBacktracking PwCTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a one-dimensional array to represent queen positions where the index represents the row and the value represents the column.
 Step 2: Use a backtracking approach to place queens one row at a time.
 Step 3: For each row, try placing a queen in each column and check if it's valid (doesn't conflict with previously placed queens).
 Step 4: A position is valid if no other queen is in the same column or diagonal.
 Step 5: If a valid position is found, place the queen and recursively try to solve for the next row.
 Step 6: If all queens are placed successfully (reached the nth row), add the current configuration to the result.
 Step 7: If a solution can't be found with the current configuration, backtrack by removing the queen and trying the next column.

Submitted Code :