Tutorialspoint
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²)
SetAlgorithmsGoogleTCS (Tata Consultancy Services)
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 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

Steps to solve by this approach:

 Step 1: Create an empty n×n board represented as a 2D array.

 Step 2: Use sets to track occupied columns and diagonals.
 Step 3: Implement a recursive backtracking function starting from row 0.
 Step 4: For each position, check if placing a queen is safe (no attacks possible).
 Step 5: If safe, place the queen and mark columns and diagonals as occupied.
 Step 6: Recursively solve for the next row and backtrack if needed.
 Step 7: Add complete board configurations to the result when all rows are filled.

Submitted Code :