Eight queens
how it works
The idea on a 4 by 4 board, as the watch page runs it.
Put queens on an by board so that no two attack: no two share a row, a column or a diagonal. Each row holds exactly one queen, so go row by row from the top. In each row, check the squares from the left, and put the queen on the first one no queen above attacks. If a row has no such square, go back: move the queen above on to its next safe square, or take it off and go back again. This page counts squares checked, one each time the method looks at a square.
| step | what happens | queens | checked so far |
|---|---|---|---|
| 2 | row 1: a1 is safe | a1 | 1 |
| 3 | row 2: a2 and b2 attacked, c2 safe | a1, c2 | 4 |
| 4 | row 3: all 4 attacked; back to row 2, on to d2 | a1, d2 | 9 |
| 5 | row 3: a3 attacked, b3 safe | a1, d2, b3 | 11 |
| 6 | row 4: all 4 attacked; back in row 3, c3 and d3 attacked, so b3 comes off | a1, d2 | 17 |
| 7 | row 2 has no square past d2, so d2 comes off | a1 | 17 |
| 8 | back to row 1: on to b1 | b1 | 18 |
| 9 to 11 | d2, then a3, then c4: a queen in every row | b1, d2, a3, c4 | 26 |
4 by 4
step 2 of 12
Queen 1 goes on a1, the first square in row 1 that no queen attacks.
what it remembers to know where it is
- row
- 1
- queens on the board
- 1
step 3 of 12
Queen 2 goes on c2, the first square in row 2 that no queen attacks.
what it remembers to know where it is
- row
- 2
- queens on the board
- 2
step 4 of 12
Row 3 has no square left to try: any not attacked has been tried already. So go back: queen 2 moves on from c2 to d2, the next square along its row that no other queen attacks.
what it remembers to know where it is
- row
- 2
- queens on the board
- 2
step 5 of 12
Queen 3 goes on b3, the first square in row 3 that no queen attacks.
what it remembers to know where it is
- row
- 3
- queens on the board
- 3
step 6 of 12
Row 4 has no square left to try, and every square further along row 3 from b3 is attacked. So queen 3 comes off.
what it remembers to know where it is
- row
- 3
- queens on the board
- 2
step 7 of 12
Row 3 has no square left to try, and every square further along row 2 from d2 is attacked. So queen 2 comes off.
what it remembers to know where it is
- row
- 2
- queens on the board
- 1
step 8 of 12
Row 2 has no square left to try: any not attacked has been tried already. So go back: queen 1 moves on from a1 to b1, the next square along its row that no other queen attacks.
what it remembers to know where it is
- row
- 1
- queens on the board
- 1
step 12 of 12
A queen in every row, and no two attack each other: that is an answer for 4 by 4.
what it remembers to know where it is
- row
- not yet
- queens on the board
- 4
Where it says not yet, nothing is held there at that moment.
the steps, in plain words
choose a step to mark the Python, a programming language, that does it
- start at the top row, trying its squares from the leftPython lines 15 and 23
- while a row is left to fill:Python lines 13 and 18
- put a queen on the row's next square that no queen attacksPython lines 16 and 17
- if there is none, go back: move the queen in the row above on to its next free square, or take it off and go back againPython lines 20 and 21
- a queen in every row is the answer; going back past the top row means there is nonePython lines 14, 24 and 25
the same in Python
The steps in plain words are what to learn. Python is a programming language, and the code below does the same steps, for those who code. Python numbers the places in a list from 0, not 1: the first number is numbers[0], the second numbers[1], and so on.
def eight_queens(n):
"""Put n queens on an n by n board so that no two share a row, a column or a diagonal.
n is a whole number from 1 to 8. Returns the first answer found, one square a row from
the top, such as "b1" for column b of row 1, or [] when there is none.
"""
columns = [] # columns[r] is the column of row r's queen, from 0
def safe(row, column): # no queen above attacks this square
return all(c != column and abs(c - column) != row - r for r, c in enumerate(columns))
def fill(row): # fill this row and every row below it
if row == n: # a queen in every row: an answer
return True
for column in range(n): # the row's squares, from the left
if safe(row, column):
columns.append(column) # put a queen here
if fill(row + 1):
return True
columns.pop() # no answer this way: take it off, try the next square
return False # no square left: go back to the row above
if not fill(0): # going back past the top row: no answer
return []
return ["abcdefgh"[c] + str(r + 1) for r, c in enumerate(columns)]
how it scales
The plot counts the squares the method checks on an by board, measured from 1 by 1 to 16 by 16.
Each mark up is ten times the one before, and each mark across adds the same number of squares to the side. The points zigzag: 6 by 6 checks 171 squares, and 7 by 7 only 42. Some boards lead quickly to an answer, and others make the method go back many times. No formula gives the count, so the plot shows points only. Question 1 in section 4 puts a ceiling and a floor on it.
squares checked, ten times more at each mark up
, how many squares each side of the board has, the same step more at each mark to the right
- an by board, the one run there is for that points only, each measured by a real run, since no single formula for the squares checked of this row is worked out here
| squares checked | time | |
|---|---|---|
| 5 | 15 | about 15 nanoseconds |
| 11 | 517 | about 517 nanoseconds |
| 16 | 160,712 | about 161 microseconds |
The squares checked are the same on any computer. The times are not: a real computer may be faster or slower than a billion a second.
make these counts yourself
Copy this script and run it with Python 3.12 or later. It counts the same steps as the plot. Where a count depends on a random shuffle, yours will differ a little.
"""Count eight queens' squares checked yourself, as the plot on this page does.
Run it with Python 3.12 or later. For each board from 1 by 1 to 16 by 16 it
prints the squares the method checks before its first answer, or before it
finds there is none. The counts are the same on any computer; only the time
differs.
"""
def eight_queens(n):
"""Put n queens on an n by n board so that no two share a row, a column or a diagonal.
n is a whole number from 1 to 8. Returns the first answer found, one square a row from
the top, such as "b1" for column b of row 1, or [] when there is none.
"""
columns = [] # columns[r] is the column of row r's queen, from 0
def safe(row, column): # no queen above attacks this square
return all(c != column and abs(c - column) != row - r for r, c in enumerate(columns))
def fill(row): # fill this row and every row below it
if row == n: # a queen in every row: an answer
return True
for column in range(n): # the row's squares, from the left
if safe(row, column):
columns.append(column) # put a queen here
if fill(row + 1):
return True
columns.pop() # no answer this way: take it off, try the next square
return False # no square left: go back to the row above
if not fill(0): # going back past the top row: no answer
return []
return ["abcdefgh"[c] + str(r + 1) for r, c in enumerate(columns)]
def count(n):
"""The same method on an n by n board, counting the squares it checks."""
columns = []
checked = 0
def safe(row, column):
return all(c != column and abs(c - column) != row - r for r, c in enumerate(columns))
def fill(row):
nonlocal checked
if row == n:
return True
for column in range(n):
checked += 1 # one square checked
if safe(row, column):
columns.append(column)
if fill(row + 1):
return True
columns.pop()
return False
fill(0)
return checked
if __name__ == "__main__":
print(f"{'board':>8} {'checked':>9}")
for n in range(1, 17):
print(f"{f'{n} by {n}':>8} {count(n):>9}")
best, worst and average
Best, worst and average usually name different inputs of one size. Here the input is alone, so each is one input and one run, the same every time. So the table has one column, under the name worst, and no average is worked out.
A case is one kind of input. A bound says how fast its cost grows as grows.
The counts are in the grid. This count has no formula, so the grid gives a floor and a ceiling instead, and how fast each grows. At 8 by 8 the floor is 8, the ceiling 2,580,480, and the run checks 876.
| worstan by board, the one run there is for that | |
|---|---|
| squares checked | measured; at least , and at most |
| how the squares checked grow in each case | |
| tight, | not worked out here: the floor and the ceiling grow differently, so no is found |
| ceiling, | |
| floor, | |
extra memory: a list of at most columns, one for each row filled, and for each of those rows a mark of where to carry on from.
Extra memory is the room it needs on top of the input itself, while it runs.
| board | squares checked | queens put down | answer |
|---|---|---|---|
| 1 by 1 | 1 | 1 | a1 |
| 2 by 2 | 6 | 2 | none |
| 3 by 3 | 18 | 5 | none |
| 4 by 4 | 26 | 8 | b1, d2, a3, c4 |
| 5 by 5 | 15 | 5 | a1, c2, e3, b4, d5 |
| 6 by 6 | 171 | 31 | b1, d2, f3, a4, c5, e6 |
| 7 by 7 | 42 | 9 | a1, c2, e3, g4, b5, d6, f7 |
| 8 by 8 | 876 | 113 | a1, e2, h3, f4, c5, g6, b7, d8 |
where the formula comes from
Two questions, each worked line by line. Question 1 bounds the count the plot draws. Question 2 counts how many boards trying every board would look at.
the move: one row at a time
the line:row 1 holds row 2 checks a1 a2, b2, c2, later d2 b1 a2, b2, c2, d2 4 by 4, from the run: each way row 1 holds its queen, row 2 checks each square once. why it is allowed: While the queens above stay put, the method checks the row from the left and never checks a square twice. Going back moves a queen further along its row while the queens above it stay. So, like a counter going up, the rows above never hold their queens the same way twice. For 4 by 4, under a1, row 2 checks a2, b2 and c2, then later d2; under b1, a2 to d2 again.
the move: ways above a row
the line:4 by 4 queens above ways at most row 1 0 1 row 2 1 4 row 3 2 4 times 3, 12 row 4 3 4 times 3 times 2, 24 Each row's ways above, at most. None passes , 24. why it is allowed: The first queen above has squares to choose from, and each next one has one column fewer, as no two share one; a diagonal may rule out more. Multiply them: a row has fewer than queens above it, so the multiplying stops before reaching 1, and is at most . For 4 by 4, row 4 has 3 queens above: at most 4 times 3 times 2, which is 24.
guess it, thenthe move: multiply, for one row
the line:why it is allowed: By lines 1 and 2: at most squares for each of at most ways. For 4 by 4, 4 times 24, which is 96.
guess it, thenthe move: add up the rows
the line:why it is allowed: By line 3, each of the rows checks at most squares. For 4 by 4, 4 times 96, which is 384; the run checks 26.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 4, with the fixed multiple 1, as is .
guess it, thenthe move: a floor
the line:board floor, , counted ceiling, 2 by 2 2 6 8 4 by 4 4 26 384 6 by 6 6 171 25,920 8 by 8 8 876 2,580,480 The run's count sits between the floor and the ceiling, and from 4 by 4 on far under the ceiling. An attacked square gets no queen, so no board that starts that way is ever tried. why it is allowed: With an answer, every row gets a queen, and each queen needs a check first. With none, the method checks every square of row 1 before it goes back past the top. For 4 by 4, at least 4, and the run checks 26; for 3 by 3, which has no answer, at least 3, and the run checks 18.
guess it, thenthe move: read the bound
the line:why it is allowed: By line 6, with the fixed multiple 1. The ceiling and the floor grow very differently, and the measured count wanders between them.
guess it, then
try it with a small : no formula gives , but at the run makes , which you can count by hand
the move: row 1
the line:why it is allowed: No queen is down yet, so any of its squares will do. For 4 by 4, a1, b1, c1 or d1.
the move: the rows below
the line:row 1 row 2 row 3 a1 b2 c3 a1 c2 b3 b1 a2 c3 b1 c2 a3 c1 a2 b3 c1 b2 a3 3 by 3, diagonals not looked at yet: 3 choices in row 1, each with 2 in row 2, each with 1 in row 3. 3 times 2 times 1, which is 6 boards. why it is allowed: Each queen above takes a column, and no two queens share one. So row 2 has one choice fewer than row 1, row 3 two fewer, and on down to 1.
guess it, thenthe move: multiply them
the line:why it is allowed: By lines 1 and 2. Whichever square row 1 takes, row 2 has one fewer left, and whichever pair, row 3 two fewer, so the choices multiply, down to 1: . For 8 by 8, 40,320 boards, before any diagonal is looked at. The method checks 876 squares there.
guess it, then
try it with a small : at , line 3 gives , which you can work out by hand
count it yourself
4 by 4, step by step. A step that takes a queen off may check nothing new.
| step | what happens | squares checked | queens put down |
|---|---|---|---|
| 1 | Put 4 queens on a 4 by 4 board so that no two share a row, a column or a diagonal. Go row by row from the top, each queen on the first square no queen attacks. | 0 | 0 |
| 2 | Queen 1 goes on a1, the first square in row 1 that no queen attacks. | 1 | 1 |
| 3 | Queen 2 goes on c2, the first square in row 2 that no queen attacks. | 4 | 2 |
| 4 | Row 3 has no square left to try: any not attacked has been tried already. So go back: queen 2 moves on from c2 to d2, the next square along its row that no other queen attacks. | 9 | 3 |
| 5 | Queen 3 goes on b3, the first square in row 3 that no queen attacks. | 11 | 4 |
| 6 | Row 4 has no square left to try, and every square further along row 3 from b3 is attacked. So queen 3 comes off. | 17 | 4 |
| 7 | Row 3 has no square left to try, and every square further along row 2 from d2 is attacked. So queen 2 comes off. | 17 | 4 |
| 8 | Row 2 has no square left to try: any not attacked has been tried already. So go back: queen 1 moves on from a1 to b1, the next square along its row that no other queen attacks. | 18 | 5 |
| 9 | Queen 2 goes on d2, the first square in row 2 that no queen attacks. | 22 | 6 |
| 10 | Queen 3 goes on a3, the first square in row 3 that no queen attacks. | 23 | 7 |
| 11 | Queen 4 goes on c4, the first square in row 4 that no queen attacks. | 26 | 8 |
| 12 | A queen in every row, and no two attack each other: that is an answer for 4 by 4. | 26 | 8 |
In all, 26 squares checked. No formula gives this count. Section 4 puts it between 4 and 384 at , and 26 lies between them.
where you meet it
Eight queens is a chess puzzle from the 1800s, and a favourite first example of going back.
teaching programming
Niklaus Wirth, who designed the Pascal language, used eight queens in 1971 to show how to write a program step by step, each step making the last one more exact.
source: Niklaus Wirth, Program Development by Stepwise Refinement (opens in a new tab), Communications of the ACM, 1971
testing Python itself
Python's own test suite solves eight queens, all 92 answers, to check that its generators work, functions that hand back one answer at a time.
source: CPython 3.12, Lib/test/test_generators.py (opens in a new tab)
counting every answer
Carry on past the first answer and you find them all. There are 2 on 4 by 4, 10 on 5 by 5, 4 on 6 by 6, 40 on 7 by 7 and 92 on 8 by 8.
source: the On-Line Encyclopedia of Integer Sequences, A000170 (opens in a new tab)
what is used instead
For a very big board, a different idea is used. Put a queen in every row first, each where the fewest queens already down attack it, even if some attack. Then, again and again, pick an attacked queen and slide it along its row to where the fewest queens attack it. Steven Minton and three colleagues showed in 1990, and again in 1992, that this solves a million queens, far past what going back can reach.
how it compares
Trying every board checks each of boards in turn. The method instead stops a board as soon as one queen is attacked, so it never looks at any board that starts that way. Carrying on for every answer costs more than stopping at the first.
| way | 8 by 8 |
|---|---|
| every board with one queen a row | 16,777,216 boards |
| every board with one queen a row and a column | 40,320 boards |
| going back, every answer | 15,720 squares checked, 92 answers |
| going back, the first answer | 876 squares checked |
| board | boards, | the method checks |
|---|---|---|
| 4 by 4 | 24 | 26 squares |
| 6 by 6 | 720 | 171 squares |
| 8 by 8 | 40,320 | 876 squares |
| 12 by 12 | 479,001,600 | 3,066 squares |