Aller au contenu principal
Interactive Algorithm Education

Visualize & Master Algorithms & Data Structures

Explore classic & modern sorting algorithms, efficient searching techniques, and interactive data structure visualizations — all with real-time step-by-step animation, comparisons, swaps, and Big-O metrics.

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
 

N-Queens

Intermediate (3/5) ~45 minutes Backtracking search Constraint checking (row/column/diagonal) Pruning dead branches Exponential worst case Prereqs: Recursion, Basic constraint reasoning
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.

Place n queens on an n×n board so that no two attack each other — no shared row, column, or diagonal.

The catch: even with one queen per row enforced up front, the search still explodes combinatorially. Backtracking tames it by rejecting partial placements the moment they become invalid, instead of building full candidates and checking later.

How It Works

  1. Try each column of the current row.
  2. Check the column and both diagonals against queens already placed.
  3. Place a queen if safe, then recurse to the next row.
  4. Prune the branch immediately when the position is attacked.
  5. Backtrack — if a row has no safe column, remove the previous queen and advance it to its next column.

Because exactly one queen sits in each row, you only track the column of each placed queen — the board state is a single array, and the safety test reduces to comparing columns and diagonal differences.

Key Insight

The solver explores the search tree depth-first and prunes as soon as a partial placement becomes invalid. That’s the entire point of backtracking: constraints are checked during construction.

  • Without pruning — C(n², n) candidate placements.
  • With pruning — roughly n! / e arrangements: still exponential, but drastically smaller.

The moment row k has no safe column, the solver stops descending and unwinds.

Worked Example

The visualizer solves the 6×6 board (N = 6). Watch the queens appear one row at a time, left to right. Early rows place quickly; then a row finds no safe column, the solver undoes the previous queen, advances it, and resumes. The final frame shows all 6 queens placed with no two sharing a row, column, or diagonal:

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

Each placed queen eliminates its entire column and both diagonals from the rows below — the safety check that makes the solution legal.

Edge Cases & Pitfalls

  • N < 4 — there is no solution for N = 2 or N = 3: the solver must report failure, not loop forever.
  • All diagonals — a queen attacks along r + c (one diagonal family) and r − c (the other). Track both sets.
  • Symmetry — rotations/reflections of one solution are all valid; a solver finds just one by default.
  • Premature cutoff — pruning must not reject a square that a deeper queen could still make safe. Safety only checks already-placed queens.

Comparison: N-Queens Search Strategies

StrategyIdeaNotes
Plain backtrackingFirst safe column, unwind on failureBaseline
Symmetry pruningSkip rotated/reflected boardsCuts ~8×
Forward checkingTrack remaining safe columns per rowPrunes earlier
Constraint propagationDomino effects before placingSudoku-style

Applications

  • Constraint satisfaction — timetabling and scheduling use the same search
  • Graph coloring — place “colors” without adjacent conflicts
  • Puzzle solving — Sudoku, crosswords, and fill-in puzzles

Practice Trajectory

  1. Trace the visualizer: note each row’s first safe column and where the first backtrack happens.
  2. Derive why N = 2 and N = 3 have no solution before running the solver.
  3. Implement the safety check using only the column array — no 2D board needed.
  4. Add symmetry pruning and count how many distinct solutions N = 6 has (4 total, 1 up to symmetry; N = 8 has 92, 12 up to symmetry).
  5. Explain why the recursion depth is exactly n, not n².