N = 4: backtracking shows up
- Input
- 4x4, colunas em ordem crescente
- Expected output
- 8 colocações, 4 retiradas, solução b4 d3 a2 c1
The first attempt on the first row dies before finishing; only the second column leads to a solution.
Eight Queens Puzzle (and N Queens)
n queens backtracking algorithm
The classic way to solve N queens is backtracking: place one queen per row, left to right, and step back whenever a row has no safe square. The Solver tab animates exactly that, placement by placement.
The first attempt on the first row dies before finishing; only the second column leads to a solution.
A total of 218 steps to the first of the 92 solutions.
A total of 3,784 steps. To find a single solution backtracking is quick; the cost is in counting all 365,596.
There are 92 solutions on the 8x8 board. If rotations and reflections count as the same, 12 fundamental solutions remain (OEIS A002562). Eleven of them generate 8 solutions each and one, symmetric under a 180 degree turn, generates only 4: 11 x 8 + 4 = 92.
It is a depth-first search that builds the answer piece by piece and undoes the last choice whenever it hits a dead end. It prunes branches that can no longer work, instead of testing every combination.
Two queens in the same row attack each other, and N queens in N rows only fit if each row has exactly one. That reduces the search from choosing N squares out of N x N to choosing one column per row.
Open the Solver tab, pick N, press Animate and adjust the speed. Queens appear and disappear while backtracking searches, and the counters show placements and removals up to the first solution.
0 of 8 queens on the board. 0 placements and 0 removals so far.
| N | Computed here | OEIS A000170 | Fundamental (A002562) | Time |
|---|---|---|---|---|
| Press Count to compute. | ||||
The count uses bitmasks and explores only half of the first row, doubling by the mirror. The fundamental column comes from the OEIS table (checked here by enumeration up to N = 11).
Everything runs in your browser: your moves and calculations are not sent to any server.