Tutorialspoint
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).
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.
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)
AlgorithmsBacktracking CapgeminiShopify
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 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

Steps to solve by this approach:

 Step 1: Initialize an empty N×N chessboard and solution storage arrays
 Step 2: Start with the first row (row = 0) and try placing a queen in each column
 Step 3: For each position, check if it's safe by verifying no conflicts with previously placed queens
 Step 4: Check column conflicts by examining all previous rows in the same column
 Step 5: Check diagonal conflicts by examining both upper-left and upper-right diagonals
 Step 6: If position is safe, place the queen and recursively solve for the next row
 Step 7: If all N queens are placed successfully, store the solution and backtrack to find more solutions

Submitted Code :