Aller au contenu principal
Data structures, algorithms, and the core CS foundations — plus an optional advanced track for expert topics.

Core Computer Science

Data structures, algorithms, and the core CS foundations — plus an optional advanced track for expert topics.

Backtracking Visualizer

N-Queens

Étape 0 / 0
Speed 100ms
Step Progress 0 / 0
Recursion Depth 0
Pruned Branches 0
Status Ready
Empty
Placing / Active
Conflict / Pruned
Solution
Placed
Step Explanation

Select an algorithm and press Play to watch the search tree explore and backtrack.

—
Pseudocode
 

Backtracking

Intermediate (3/5) ~3 hours Constraint satisfaction problems Incremental candidate construction Pruning Depth-first search of the solution space Optimization vs brute-force search Prereqs: Recursion, Dynamic Programming
Quick Reference

N-Queens

N-Queens places n queens on an n×n board so that no two queens attack each other (no shared row, column, or diagonal). Backtracking places queens row by row and undoes placements that lead to dead ends.

Difficulty: Intermediate (3/5) backtracking

Complexity

Best Time
O(n!)
Average Time
O(n!)
Worst Time
O(n!)
Space
O(n)

When to Use

Use N-Queens to learn backtracking, constraint satisfaction, and the classic board-search pattern that generalizes to scheduling and puzzle solving.

Pros

  • Clean demonstration of the backtracking pattern
  • The board makes every prune/backtrack visible
  • Pruning via precomputed attack sets speeds it up massively

Cons

  • Exponential worst case O(n!)
  • Simple solver returns only the first solution
  • Checking diagonals naively is O(n) per move

History

The n-queens problem was first posed by Max Bezzel in 1848 and solved for n=8 by Franz Nauck in 1850. It became a classic programming exercise in the early days of computer science.

Backtracking is a systematic way to search for solutions by building candidates one decision at a time, and the moment a partial candidate cannot possibly lead to a valid solution, abandoning it and undoing the last decision. It is depth-first search over the space of partial candidates.

The Core Pattern

Every backtracking algorithm has the same skeleton:

  1. Choose — make the next decision (e.g. place a queen, pick a value).
  2. Check — is the partial solution still valid? If not, prune and undo.
  3. Recurse — move to the next decision.
  4. Undo — on failure, remove the last choice and try the next option.
function solve(state):
  if state is complete: record solution; return
  for each candidate in ordered options:
    if valid(state + candidate):
      apply(candidate)
      if solve(state) succeeds: return true
      undo(candidate)          # backtrack
  return false

Key Ideas

Pruning is what separates backtracking from brute force. By checking constraints during construction — rather than after a full candidate exists — the algorithm cuts off entire subtrees.

N-Queens prunes every attacked position before recursing. Without pruning it would enumerate C(n², n) boards instead of exploring only O(n!) safe partial placements.

Undo must be exact. Each recursive frame must restore the state it modified, or later branches will see corrupt state. This is why backtracking solutions mutate a shared board/array rather than copying it.

Famous Backtracking Problems

ProblemConstraintState
N-QueensNo shared row/col/diagonalBoard of placed queens
SudokuRow/col/box uniquenessFilled grid
PermutationsUse each element onceChosen prefix
Subset SumSum ≤ targetSelected subset
Graph ColoringAdjacent colors differVertex colors
TechniqueChoiceReuse
Brute forceEnumerate allNone
BacktrackingEnumerate + pruneNone
Dynamic ProgrammingExplore all, store statesHeavy

Backtracking explores the space and prunes but stores no table; DP shares subproblems.

  • Overlapping subproblems → DP.
  • Each branch essentially unique (N-Queens, Sudoku) → backtracking.

Optimization Techniques

  • Heuristic ordering (MRV) — choose the decision with the fewest options first; this prunes earlier and dramatically shrinks the tree.
  • Forward checking — after each placement, eliminate candidates that became impossible.
  • Symmetry breaking — skip mirror images and rotations of equivalent solutions.
  • Iterative deepening — combine DFS with a depth limit for state spaces of unknown size.

Practice Trajectory

Start with permutations and subsets, then N-Queens (the classic board), then Sudoku (multi-constraint), then graph coloring and Hamiltonian paths. For each, focus on the prune condition — that’s where the performance lives.