N-Queens Problem
Algorithm Optimization
Combinatorial Puzzles
Computational Limits
Computer Science Challenges

Solving N-Queens Problem... How far can we go?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The N-Queens problem asks how to place N queens on an N x N board so no two queens attack each other. It is a classic search problem used to teach pruning, symmetry reduction, and bit-level optimization. The interesting question is not only how to solve it, but how far practical solvers can scale under different goals.

Baseline Backtracking Approach

A standard solver places one queen per row and checks whether a candidate column is safe from previous placements.

python
1def solve_n_queens(n: int):
2    cols = set()
3    diag1 = set()  # row - col
4    diag2 = set()  # row + col
5    board = [-1] * n
6    solutions = []
7
8    def dfs(r: int):
9        if r == n:
10            solutions.append(board.copy())
11            return
12
13        for c in range(n):
14            if c in cols or (r - c) in diag1 or (r + c) in diag2:
15                continue
16
17            cols.add(c)
18            diag1.add(r - c)
19            diag2.add(r + c)
20            board[r] = c
21
22            dfs(r + 1)
23
24            board[r] = -1
25            cols.remove(c)
26            diag1.remove(r - c)
27            diag2.remove(r + c)
28
29    dfs(0)
30    return solutions
31
32print(len(solve_n_queens(8)))

This is clear and correct, but set-based checks become a bottleneck as N grows.

Bitmask Optimization

Bitmasks replace sets with integer operations, which are significantly faster in tight recursion loops.

python
1def count_n_queens_bitmask(n: int) -> int:
2    full = (1 << n) - 1
3
4    def dfs(cols: int, d1: int, d2: int) -> int:
5        if cols == full:
6            return 1
7
8        total = 0
9        available = full & ~(cols | d1 | d2)
10
11        while available:
12            bit = available & -available
13            available -= bit
14            total += dfs(
15                cols | bit,
16                ((d1 | bit) << 1) & full,
17                (d2 | bit) >> 1,
18            )
19
20        return total
21
22    return dfs(0, 0, 0)
23
24print(count_n_queens_bitmask(12))

For counting problems, bitmasks are usually the biggest single performance improvement.

Symmetry Reduction

The board is symmetric around the vertical axis. You can reduce top-level work by exploring only half of first-row placements and mirroring counts.

For odd N, the center column must be handled separately.

Symmetry reduction plus bitmasks often gives major speedups for counting mode.

What "How Far" Means

Scalability depends on task definition:

  • Find one valid board.
  • Count all solutions.
  • Enumerate all board layouts.

Finding one solution scales much farther than full enumeration. Counting all solutions is expensive but practical for moderate to high N in optimized implementations.

Language matters too. Python can go far with bitmasks, but high-end records are usually achieved with compiled languages and aggressive low-level tuning.

Parallel Search Strategy

N-Queens branches naturally. You can split by first-row or first-two-row placements and process branches in parallel.

python
1from multiprocessing import Pool
2
3def branch_task(args):
4    n, first_col = args
5    # branch-specific counting logic would go here
6    return 0
7
8def parallel_count_driver(n: int):
9    with Pool() as pool:
10        parts = pool.map(branch_task, [(n, c) for c in range(n)])
11    return sum(parts)

Parallelism helps, but pruning quality remains the primary factor.

Verification and Correctness Checks

Optimization introduces risk. Always validate against known small-board counts:

  • 'N=4 has 2 solutions.'
  • 'N=8 has 92 solutions.'

Use these values in automated tests before trusting performance benchmarks.

Practical Engineering Lessons

N-Queens teaches techniques that transfer to real systems:

  • Constraint propagation.
  • Search-space pruning.
  • Symmetry-aware decomposition.
  • Representation tradeoffs between readability and speed.

These patterns appear in scheduling, placement, and other combinatorial optimization problems.

Common Pitfalls

  • Benchmarking enumeration and counting as if they were the same workload.
  • Keeping full board matrices in recursion when only column and diagonal state is needed.
  • Implementing symmetry reduction incorrectly for odd board sizes.
  • Reporting performance without correctness checks on known counts.
  • Assuming parallelism can compensate for weak pruning.

Summary

  • Backtracking solves N-Queens conceptually, while bitmasks make it fast in practice.
  • Symmetry reduction significantly reduces top-level search work.
  • Practical limits depend on whether you seek one solution, counts, or full listings.
  • Parallelization helps after pruning and representation are already optimized.
  • Always verify optimized solvers against known small N counts before scaling up.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.