The N-Queens Puzzle and Backtracking, Explained

After reading this you will understand how backtracking search places N queens on a chessboard, why it prunes billions of dead arrangements without ever visiting them, and how to count the solutions for any board size.

What the puzzle is

The task is simple to state. Put N queens on an N×N chessboard so that no two attack each other. A queen attacks along her row, her column, and both diagonals. So no two queens may share a row, a column, or a diagonal.

On the standard 8×8 board this is the eight-queens puzzle. There are 92 ways to do it. That number is tiny next to the number of ways to drop 8 queens on 64 squares, which is \binom{64}{8} = 4{,}426{,}165{,}368, about 4.4 billion. A blind search that checked every arrangement would waste almost all of its work. Backtracking finds all 92 solutions after examining only a few thousand partial placements.

The hook is the retreat. The algorithm marches forward placing queens, and when a row offers no safe square it does not give up. It steps back one row, moves the earlier queen, and tries again. That single idea, undo and retry, is the whole method.

Why one queen per row

The first useful observation cuts the problem down before any search begins. Because no two queens can share a row, and you need N queens on N rows, every row holds exactly one queen. So a solution is just a choice of column for each row.

Write the answer as a list c_0, c_1, \dots, c_{N-1} where c_r is the column of the queen in row r. This turns a placement problem into a sequence of N choices, each from N columns. The raw count of such lists is N^N, which for N = 8 is 8^8 = 16{,}777{,}216.

Two more constraints trim it further. No shared column means the list must have distinct values, so it is a permutation. That drops the count to N! = 40{,}320 for N = 8. The diagonal rule removes almost all of those, leaving 92.

The attack test

To decide whether a new queen in row r, column c is safe against a queen already placed in row r', column c', you check three things.

c \ne c', \quad r + c \ne r' + c', \quad r - c \ne r' - c'

The first inequality forbids the same column. The second forbids the same anti-diagonal: every square on one anti-diagonal shares the value r + c. The third forbids the same main diagonal, where r - c is constant. You never need to test the row, because you place exactly one queen per row by construction.

A faster equivalent test uses one comparison for both diagonals. Two queens sit on a common diagonal when the row gap equals the column gap in absolute value.

|r - r'| = |c - c'|

Here |r - r'| is the number of rows between the queens and |c - c'| is the number of columns. When those match, the queens lie on a 45-degree line, so they attack. When they differ, the diagonals are clear.

How backtracking searches

The algorithm builds the column list one row at a time and abandons any partial list the moment it becomes illegal. In pseudocode form the recursion is short:

  1. If every row has a queen, record a solution and return.
  2. For the current row, try each column from 0 to N-1.
  3. If that column is safe against all queens placed so far, place the queen and recurse on the next row.
  4. When the recursion returns, remove the queen (this is the backtrack) and try the next column.
  5. If no column in the current row is safe, return to the previous row.

The power lives in step 3. When a partial placement of the first k rows already fails, every one of the N^{N-k} ways of filling the remaining rows is thrown out at once, unvisited. Backtracking never enumerates those subtrees. That is why 92 solutions fall out of a few thousand node visits instead of billions.

The search tree has one node per legal partial placement. For N = 8 the tree has 2057 nodes and the algorithm hits 1965 dead ends (partial rows that cannot be extended) on the way to 92 leaves. Compare that with the 4.4 billion full arrangements a naive check would face.

Reproducing the 8×8 run

Run the visualizer with the default N = 8 board. Watch the first few decisions, which the search always makes the same way when it tries columns left to right.

  1. Row 0: place at column 0. Nothing attacks it yet.
  2. Row 1: column 0 shares a column, column 1 is on the diagonal (|1-0| = |1-0|). Column 2 is safe. Place it.
  3. Row 2: columns 0 and 2 are taken. Column 1 hits the row-1 queen diagonally (|2-1| = |1-2|). Column 3 hits row 1 too. Column 4 is safe. Place it.
  4. Row 3: the safe column is 1. Place it.
  5. Row 4: the safe column is 3. Place it.
  6. Row 5: no column survives all four diagonal and column tests. Dead end. Backtrack.

The retreat at row 5 undoes the row-4 queen and tries her next column. Follow this far enough and the first full solution the search reports is the column list 0, 4, 7, 5, 2, 6, 1, 3. You can read it straight off the board: row 0 at column 0, row 1 at column 4, and so on. Every solution to the 8-queens puzzle is a permutation of the digits 0 through 7 with no two on a diagonal.

Counting solutions across board sizes

The solution count grows fast but not smoothly. The 2×2 and 3×3 boards have zero solutions: they are too cramped for the diagonal rule to leave room. Every board from 4×4 up has at least one.

Number of distinct solutions by board size, and count up to symmetry
NAll solutionsUp to symmetry
111
421
5102
641
7406
89212
935246

The second column counts every board separately. The third counts only boards that differ after you remove the 8 symmetries of the square (4 rotations and their mirrors). The 92 solutions for N = 8 collapse to 12 essentially different ones. Notice that N = 6 dips to 4 solutions while N = 5 has 10. The count is not monotone.

Total solution count rising with N, with the dip at N = 6 breaking any smooth trend.

Watch the search tree shrink

The instructive thing a static page cannot show is how much pruning cuts the work as N grows. The permutation count N! is a floor on what a column-distinct search would face, yet backtracking visits far fewer nodes because it drops diagonal failures early.

For N = 4 the search visits 16 tree nodes to find 2 solutions; for N = 8 it visits 2057 nodes for 92 solutions; for N = 10 it visits 35539 nodes for 724 solutions. The naive permutation count N! for these is 24, 40320 and 3628800, so backtracking examines a shrinking fraction of the permutations: 67%, 5.1% and 0.98%.

Common mistakes

Three errors trip up people writing or reasoning about this search.

Forgetting to undo the queen
Backtracking only works if step 4 actually removes the queen before trying the next column. Leave her on the board and the state corrupts, and the search reports placements that share squares.
Testing the row
Adding a row check wastes time and hides a bug. If you place one queen per row by design, no two can ever share a row, so the row test is always true and adds nothing.
Confusing the two symmetry counts
The 8-queens puzzle has 92 solutions but only 12 fundamental ones. Reporting 12 as "the answer" is fine only if you say "up to rotation and reflection." Most solvers, including this visualizer, count all 92.

Do not read backtracking as a fast general method. It is worst-case exponential. It shines here because the diagonal constraints fail early and often, so most branches die near the root. Change the problem so that failures only appear deep in the tree and backtracking crawls.

How dead ends distribute

The number of dead ends the search hits gives a feel for how hard a board is. A dead end is a legal partial placement of the first k rows with no safe square in row k. For N = 8 the search hits 1965 of them before finishing.

Nodes visited climb steeply with N, roughly multiplying by 4 to 5 each step, while the visible board still looks manageable.

Each step up in N multiplies the work by roughly 4 to 5. From N = 8 (2057 nodes) to N = 12 (856189 nodes) the cost grows about 416-fold. This is why a browser visualizer stays smooth up to modest board sizes but slows sharply past N = 14 or so.

Related tools

The N-queens puzzle sits alongside other classic search and constraint toys on this site. The Knight's Tour also visits a board under movement rules and uses a greedy heuristic that avoids most backtracking. The Four Color Map is another constraint-satisfaction problem where you assign labels under adjacency rules. For the recursion pattern itself, the Tower of Hanoi shows a clean recursive unfolding, and the Wave Function Collapse tool collapses possibilities on a grid much as this search collapses column choices. If you want to see combinatorial explosion measured directly, the Fifteen Puzzle and its parity argument make a good companion.

Frequently asked questions

Why is there no solution for N = 2 or N = 3?

The boards are too small. On 2×2, any two squares share a row, column, or diagonal. On 3×3, a first queen and the distinct-column, distinct-diagonal rules leave no legal spot for a third queen. Every board from 4×4 upward does have at least one solution.

How many solutions does the 8×8 board have?

92 in total. Removing the 8 symmetries of the square (4 rotations and their mirror images) leaves 12 fundamentally different solutions. Most of the 12 have 8 symmetric copies; a few have fewer because they are partly symmetric themselves, which is why 12 times 8 does not land exactly on 92.

Is backtracking the fastest way to count solutions?

For finding solutions on a board a person can watch, yes. For counting solutions on very large boards, faster methods use bitmask arithmetic (one integer each for column, main-diagonal and anti-diagonal occupancy) and constraint propagation. Those are the same backtracking idea with cheaper per-node work, not a different algorithm.

What is the difference between a dead end and a backtrack?

A dead end is a partial placement with no safe square in the next row. A backtrack is the action of retreating one row and trying the previous queen's next column. Every dead end triggers at least one backtrack, but a backtrack also happens after a solution is recorded, when the search resumes looking for more.

Can the same method solve related puzzles?

Yes. Swap the attack test and the same code solves the n-rooks problem (only rows and columns matter, giving N! solutions) or the peaceable-queens variant. The frame stays fixed: choose one item per row, test against earlier choices, undo on failure.