← Back to list

N-Queens Problem: An Overview

The N-Queens Problem is a classic combinatorial problem in computer science and mathematics. It involves placing N chess queens on an N × N…

Kavya · 2025-01-14 12:11 · 0 claps · 5.5 min read paywalled
#n-queens-problem #recursion #java #programming #software-development
Open on Medium ↗
Wiki topics: 💻 · Programming 📐 · Mathematics 🔬 · Science · General

N-Queens Problem: An Overview

The N-Queens Problem is a classic combinatorial problem in computer science and mathematics. It involves placing N chess queens on an N × N chessboard such that no two queens threaten each other.

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.

The goal is to find all possible arrangements or determine if at least one arrangement exists for the given board size (N).

Where is the N-Queens Problem Helpful?

  1. Artificial Intelligence — Used in AI algorithms for constraint satisfaction problems (CSP).
  2. Backtracking Algorithms — Demonstrates how recursive backtracking techniques work efficiently.
  3. Optimization Problems — Serves as a base model for real-world optimization problems like job scheduling, VLSI design, and resource allocation.
  4. Game Theory — Helps in understanding spatial arrangement strategies.
  5. Mathematics and Computation — Solves combinatorics and permutation problems effectively.

Key Concepts Related to N-Queens Problem

Backtracking Algorithm:

  • Used to build a solution incrementally.
  • Backtracks when the current solution violates constraints.
  • Efficiently explores all possible arrangements.

Recursion:

  • Breaks down the problem into smaller subproblems, solving one queen placement at a time.

Constraint Satisfaction Problems (CSP):

  • Models like Sudoku and graph coloring use similar approaches for constraint enforcement.

State Space Tree:

  • Each node represents a partial solution.
  • The tree branches are pruned when a conflict is detected.

Pseudocode for N-Queens Problem

function solveNQueens(n):
    initialize board[n][n] with 0
    if placeQueens(board, 0, n) is true:
        print solution
    else:
        print "No solution exists"

function placeQueens(board, row, n):
    if row == n:
        return true
    for col from 0 to n-1:
        if isSafe(board, row, col, n):
            place queen at board[row][col]
            if placeQueens(board, row + 1, n) is true:
                return true
            remove queen from board[row][col]
    return false

function isSafe(board, row, col, n):
    check column
    check upper diagonal
    check lower diagonal
    if no threats:
        return true
    else:
        return false

Java Code Using Recursion

import java.util.Arrays;

public class NQueens {

    // Function to print the board
    static void printBoard(int[][] board, int N) {
        for (int[] row : board) {
            for (int cell : row) {
                System.out.print(cell == 1 ? "Q " : ". ");
            }
            System.out.println();
        }
        System.out.println();
    }
    // Main function to solve the problem
    public static boolean solveNQueens(int N) {
        int[][] board = new int[N][N]; // Initialize the board with zeros

        if (placeQueens(board, 0, N)) { // Start placing queens from row 0
            printBoard(board, N);      // Print the board if solution exists
            return true;
        } else {
            System.out.println("No solution exists.");
            return false;
        }
    }
    // Recursive function to place queens
    static boolean placeQueens(int[][] board, int row, int N) {
        if (row == N) { // Base case: All queens are placed
            return true;
        }
        for (int col = 0; col < N; col++) {
            if (isSafe(board, row, col, N)) { // Check if it's safe to place the queen
                board[row][col] = 1; // Place the queen
                // Recur for the next row
                if (placeQueens(board, row + 1, N)) {
                    return true;
                }
                // Backtrack and remove the queen
                board[row][col] = 0; 
            }
        }
        return false; // Return false if no position is possible
    }
    // Function to check if placing a queen is safe
    static boolean isSafe(int[][] board, int row, int col, int N) {
        // Check column
        for (int i = 0; i < row; i++) {
            if (board[i][col] == 1) {
                return false;
            }
        }
        // Check upper diagonal (left)
        for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
            if (board[i][j] == 1) {
                return false;
            }
        }
        // Check upper diagonal (right)
        for (int i = row, j = col; i >= 0 && j < N; i--, j++) {
            if (board[i][j] == 1) {
                return false;
            }
        }
        return true; // Safe position
    }
    // Main driver
    public static void main(String[] args) {
        int N = 8; // Define the size of the board (8-Queens problem)
        solveNQueens(N);
    }
}

Explanation of the Code

Board Initialization:

  • A 2D array represents the board, initialized with 0 indicating empty cells.

Recursive Placement:

  • The placeQueens() function attempts to place a queen in each row.
  • It backtracks when it finds an invalid configuration.

Safety Check:

  • The isSafe() function checks whether placing a queen at a specific position violates constraints.

Backtracking:

  • If placing a queen leads to failure, it undoes the move and tries the next column.

Termination Condition:

  • The function stops when all queens are successfully placed.

Time Complexity Analysis

The worst-case time complexity of the N-Queens problem is O(N!), where N is the number of queens.

  • Each row has N possibilities.
  • The next row has N-1 possibilities, and so on.

Space Complexity:

  • O(N²) for storing the board (2D array).
  • O(N) for recursion stack depth.

Output for N = 4

. Q . . 
. . . Q 
Q . . . 
. . Q .

This is one of the valid solutions for N = 4.

Additional Insights on the N-Queens Problem

1. Multiple Solutions and Counting Approaches

  • The N-Queens problem may have multiple valid solutions, especially for larger board sizes (N > 4).
  • Instead of finding just one solution, we can modify the algorithm to count all possible solutions by removing the return true; statement inside the recursive function.

Example change:

static int countSolutions = 0;
static void countNQueensSolutions(int[][] board, int row, int N) {
     if (row == N) {
         countSolutions++;
         return;     
}
      for (int col = 0; col < N; col++) {
         if (isSafe(board, row, col, N)) {
             board[row][col] = 1;
             countNQueensSolutions(board, row + 1, N);
             board[row][col] = 0; // Backtrack        
         }     
      } 
}

Output for N = 8:

Total Solutions: 92

2. Optimized Approaches Using Bit Manipulation

The above recursive approach uses O(N²) space for the board, but this can be reduced to O(N) by using bitwise masks to track occupied columns and diagonals:

  • Maintain 3 boolean arrays to track safe placements:
  1. Columns — Tracks columns that are occupied.
  2. Diagonal1 (/) — Tracks left diagonals.
  3. Diagonal2 () — Tracks right diagonals.
static void solveNQueensOptimized(int n) {
    boolean[] cols = new boolean[n];         // Columns
    boolean[] diag1 = new boolean[2 * n - 1]; // Diagonal /
    boolean[] diag2 = new boolean[2 * n - 1]; // Diagonal \
    int[] board = new int[n];
    solve(0, n, cols, diag1, diag2, board);
    }
static void solve(int row, int n, boolean[] cols, boolean[] diag1, boolean[] diag2, int[] board) {
    if (row == n) {
        printSolution(board, n);
        return;
    }
    for (int col = 0; col < n; col++) {
        if (cols[col] || diag1[row - col + n - 1] || diag2[row + col]) continue;
        // Mark columns and diagonals as occupied
        cols[col] = diag1[row - col + n - 1] = diag2[row + col] = true;
        board[row] = col;
        solve(row + 1, n, cols, diag1, diag2, board);
        // Backtrack
        cols[col] = diag1[row - col + n - 1] = diag2[row + col] = false;
    }
}
  • Why is this better?
  • Reduces space complexity to O(N).
  • Speeds up diagonal checks using precomputed boolean arrays instead of iterating.

3. Applications in Real-World Problems

  • Robotics and Autonomous Systems: Finding non-colliding paths for multiple robots is analogous to placing non-threatening queens.
  • VLSI Design: Optimal placement of electronic components to avoid interference, similar to the constraint satisfaction in N-Queens.
  • Scheduling Problems: Allocating time slots for exams or meetings without conflicts mirrors N-Queens constraints.
  • Cryptography: The constraint satisfaction model forms the foundation of encryption algorithms and puzzle-solving techniques.

4. Alternative Solving Methods

  • Heuristic Search (Hill Climbing): Instead of backtracking, heuristic methods like simulated annealing or genetic algorithms can find solutions faster, especially for larger values of N. However, these may not always guarantee the discovery of all solutions.
  • Dynamic Programming: Although less common for N-Queens, dynamic programming can reduce redundant computations in certain constraint-based problems.

5. Fun Facts About N-Queens

  • The 8-Queens Problem was first proposed by Max Bezzel in 1848.
  • The problem is an example of NP-hard problems, meaning finding solutions becomes exponentially difficult as N increases.
  • For N > 1, no solution exists for N = 2 or N = 3, which makes them exceptions!

Conclusion

The N-Queens Problem serves as a foundational concept in programming, AI, and optimization. It demonstrates how backtracking, recursion, and constraint satisfaction are applied in complex real-world scenarios.

Key Takeaways

  • The N-Queens Problem is an excellent demonstration of backtracking algorithms.
  • It can be extended to solve generalized CSP problems in AI and optimization.
  • The recursive approach, although simple, demonstrates the importance of pruning search trees for efficiency.
  • Recursive approaches solve the problem effectively for smaller boards.
  • Optimized algorithms using bit manipulation handle larger boards more efficiently.
  • This problem provides insights into AI algorithms, heuristic search, and mathematical modeling.

메타데이터
post_id
e7b2b3cc0bd5
slug
n-queens-problem-an-overview-e7b2b3cc0bd5
url
https://medium.com/@kavya1234/n-queens-problem-an-overview-e7b2b3cc0bd5
canonical_url
https://medium.com/@kavya1234/n-queens-problem-an-overview-e7b2b3cc0bd5
author_url
https://medium.com/@kavya1234
status
ok
fetched_at
2026-07-27 12:21:05