Skip to content
StackDecode
BacktrackingAnimated

N-Queens Problem

Place queens row by row, backing up when a square is attacked.

Time

O(n!)

Extra space

O(n)

Use it for

Constraint-satisfaction demo.

How it works

  1. Place one queen per row, top to bottom.
  2. In each row, find the columns not attacked by an earlier queen (same column or same diagonal).
  3. Try a safe column and move to the next row. If a row has no safe column, that is a dead end.
  4. Backtrack: lift the previous queen and try its next safe column. Stop at the first full board.
  5. Pruning dead ends early is what makes this feasible compared with testing every arrangement.

Watch it run

Loading animation…