codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🧮

Data Structures & Algorithms

37 / 65 topics
36Backtracking Basics37N-Queens Problem38Sudoku Solver39Maze Solving using Backtracking
Tutorials/Data Structures & Algorithms/N-Queens Problem
🧮Data Structures & Algorithms

N-Queens Problem

Updated 2026-04-20
3 min read

N-Queens Problem

Introduction

The N-Queens problem is a classic combinatorial challenge that involves placing N queens on an N×N chessboard such that no two queens threaten each other. A queen can attack any piece that shares the same row, column, or diagonal. Therefore, the goal is to find all possible configurations of N queens on the board where none of them are in a position to capture another.

This problem is often used as an example to demonstrate backtracking algorithms due to its recursive nature and constraint satisfaction requirements. In this tutorial, we will explore how to solve the N-Queens problem using backtracking, providing detailed explanations, code examples, and best practices.

Understanding the Problem

Constraints

  1. No two queens can be in the same row.
  2. No two queens can be in the same column.
  3. No two queens can be on the same diagonal (both main diagonals).

Objective

Find all possible configurations where N queens are placed on an N×N chessboard without any of them being able to capture another.

Backtracking Approach

Backtracking is a general algorithm for finding all (or some) solutions to computational problems, notably constraint satisfaction problems, that incrementally builds candidates to the solutions and abandons a candidate ("backtracks") as soon as it determines that the candidate cannot possibly be completed to a valid solution.

Steps in Backtracking

  1. Choose: Select a position for the next queen.
  2. Explore: Recursively attempt to place queens in subsequent rows.
  3. Backtrack: If placing a queen leads to an invalid configuration, undo the placement and try another position.

Implementation

We will implement the N-Queens problem using Python. The code will include functions to check if a queen can be placed safely on the board, to solve the problem recursively, and to print all solutions.

Code Example

def is_safe(board, row, col):
    # Check this row on left side
    for i in range(col):
        if board[row][i] == 1:
            return False

    # Check upper diagonal on left side
    for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
        if board[i][j] == 1:
            return False

    # Check lower diagonal on left side
    for i, j in zip(range(row, len(board), 1), range(col, -1, -1)):
        if board[i][j] == 1:
            return False

    return True

def solve_n_queens_util(board, col):
    # base case: If all queens are placed then return true
    if col >= len(board):
        return True

    # Consider this column and try placing this queen in all rows one by one
    for i in range(len(board)):
        if is_safe(board, i, col):
            # Place this queen in board[i][col]
            board[i][col] = 1

            # recur to place rest of the queens
            if solve_n_queens_util(board, col + 1):
                return True

            # If placing queen in board[i][col] doesn't lead to a solution,
            # then remove queen from board[i][col]
            board[i][col] = 0

    # if the queen cannot be placed in any row in this column col then return false
    return False

def solve_n_queens(n):
    board = [[0 for _ in range(n)] for _ in range(n)]

    if not solve_n_queens_util(board, 0):
        print("Solution does not exist")
        return False

    # Print the solution
    for row in board:
        print(" ".join(str(x) for x in row))
    return True

# Example usage
n = 4
solve_n_queens(n)

Explanation of the Code

  1. is_safe(board, row, col): This function checks if it's safe to place a queen at board[row][col]. It verifies that no other queens are in the same row, column, or diagonal.

  2. solve_n_queens_util(board, col): This is a recursive utility function that attempts to place queens one by one in different columns. If placing a queen leads to an invalid configuration, it backtracks and tries another position.

  3. solve_n_queens(n): This function initializes the board and calls the utility function to solve the N-Queens problem. It also prints the solution if found.

Best Practices

  1. Optimization: The above implementation can be optimized by using additional data structures to keep track of columns and diagonals that are already occupied, reducing the number of checks needed in is_safe.

  2. Iterative Approach: For very large values of N, consider using an iterative approach with a stack to avoid deep recursion issues.

  3. Parallelization: If you need to find all solutions for large N, consider parallelizing the search space across multiple threads or processes.

  4. Testing: Ensure thorough testing with different values of N, including edge cases like N=1 and N=2, where no solution exists.

Conclusion

The N-Queens problem is a fascinating example of how backtracking can be applied to solve constraint satisfaction problems. By understanding the constraints and using an efficient backtracking approach, we can find all possible configurations for placing N queens on an N×N chessboard. This tutorial provides a comprehensive guide to solving the N-Queens problem, including code examples and best practices for implementation.

By mastering this problem, you will gain valuable insights into recursive algorithms, constraint satisfaction, and optimization techniques that are applicable in various domains of computer science and software engineering.


PreviousBacktracking BasicsNext Sudoku Solver

Recommended Gear

Backtracking BasicsSudoku Solver