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
- Place one queen per row, top to bottom.
- In each row, find the columns not attacked by an earlier queen (same column or same diagonal).
- Try a safe column and move to the next row. If a row has no safe column, that is a dead end.
- Backtrack: lift the previous queen and try its next safe column. Stop at the first full board.
- Pruning dead ends early is what makes this feasible compared with testing every arrangement.
Watch it run
Loading animation…