Skip to content

Eight queens

puzzles

Level 2 of 3

Also called The eight queens puzzle and N queens, by backtracking.

how it works

The idea on a 4 by 4 board, as the watch page runs it.

Put nn queens on an nn by nn 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.

stepwhat happensqueenschecked so far
2row 1: a1 is safea11
3row 2: a2 and b2 attacked, c2 safea1, c24
4row 3: all 4 attacked; back to row 2, on to d2a1, d29
5row 3: a3 attacked, b3 safea1, d2, b311
6row 4: all 4 attacked; back in row 3, c3 and d3 attacked, so b3 comes offa1, d217
7row 2 has no square past d2, so d2 comes offa117
8back to row 1: on to b1b118
9 to 11d2, then a3, then c4: a queen in every rowb1, d2, a3, c426
4 by 4, as the run goes. A queen at a1 leads nowhere, so the method goes back at steps 4, 6, 7 and 8, the last moving it on to b1. Then every row fills.
  • acdbbdac

    4 by 4

4 by 4's choices, as the run makes them. Each level is a row from the top, each letter the column of that row's queen. Under a1, c2 meets a row with no safe square, and so does b3 under d2; b1, d2, a3, c4 fills every row. Each place is a queen put down, 8 in all; a marked place is where a path stops.
Four by four: 8 moments of its 12 steps, the steps between them left for the watch page
  1. step 2 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  2. step 3 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  3. step 4 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  4. step 5 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  5. step 6 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  6. step 7 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  7. step 8 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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

    watch from here

  8. step 12 of 12

    abcd1234a1b1c1d1a2b2c2d2a3b3c3d3a4b4c4d4

    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.

    watch from here

the steps, in plain words
  1. start at the top row, trying its squares from the leftPython lines 15 and 23
  2. while a row is left to fill:Python lines 13 and 18
  3. put a queen on the row's next square that no queen attacksPython lines 16 and 17
  4. 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
  5. 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 nn by nn 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

102104106051015101102103104105106051015101102103104105106051015

nn, how many squares each side of the board has, the same step more at each mark to the right

  • an nn by nn board, the one run there is for that nnpoints only, each measured by a real run, since no single formula for the squares checked of this row is worked out here
how long these checks take, at a billion a second
nnsquares checkedtime
515about 15 nanoseconds
11517about 517 nanoseconds
16160,712about 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 nn alone, so each nn 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 nn 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.

what each case costs, and how fast that cost grows; section 4 works out every formula in it
worstan nn by nn board, the one run there is for that nn
squares checkedmeasured; at least nn, and at most n2×n!n^2 \times n!
how the squares checked grow in each case
tight, Θ\Thetanot worked out here: the floor and the ceiling grow differently, so no Θ\Theta is found
ceiling, OOO(n2×n!)O(n^2 \times n!)
floor, Ω\OmegaΩ(n)\Omega(n)

extra memory: a list of at most nn 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.

boardsquares checkedqueens put downanswer
1 by 111a1
2 by 262none
3 by 3185none
4 by 4268b1, d2, a3, c4
5 by 5155a1, c2, e3, b4, d5
6 by 617131b1, d2, f3, a4, c5, e6
7 by 7429a1, c2, e3, g4, b5, d6, f7
8 by 8876113a1, e2, h3, f4, c5, g6, b7, d8
Counted by the run, from 1 by 1 to 8 by 8, the most the watch page takes. Queens put down counts each time a queen goes on a square, a queen moved on counted again: 4 by 4 puts down 8 to end with 4. 2 by 2 and 3 by 3 have no answer, so the method tries everything there.

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.

Question 1: between what ceiling and what floor do the squares checked, CC, lie on an nn by nn board?
  1. the move: one row at a time

    the line:
    for each way the rowsabove hold their queens,a row checks nosquare twice\begin{gathered} \text{for each way the rows} \\ \text{above hold their queens,} \\ \text{a row checks no} \\ \text{square twice} \end{gathered}
    row 1 holdsrow 2 checks
    a1a2, b2, c2, later d2
    b1a2, 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.

  2. the move: ways above a row

    the line:
    the rows above hold theirqueens in at most n! ways\begin{gathered} \text{the rows above hold their} \\ \text{queens in at most } n! \text{ ways} \end{gathered}
    4 by 4queens aboveways at most
    row 101
    row 214
    row 324 times 3, 12
    row 434 times 3 times 2, 24
    Each row's ways above, at most. None passes 4!4!, 24.

    why it is allowed: The first queen above has nn 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 nn queens above it, so the multiplying stops before reaching 1, and is at most n!n!. For 4 by 4, row 4 has 3 queens above: at most 4 times 3 times 2, which is 24.

  3. the move: multiply, for one row

    the line:
    one row checks at mostn×n! squares\begin{gathered} \text{one row checks at most} \\ n \times n! \text{ squares} \end{gathered}

    why it is allowed: By lines 1 and 2: at most nn squares for each of at most n!n! ways. For 4 by 4, 4 times 24, which is 96.

  4. the move: add up the rows

    the line:
    C≤n×n!×nC \le n \times n! \times n

    why it is allowed: By line 3, each of the nn rows checks at most n×n!n \times n! squares. For 4 by 4, 4 times 96, which is 384; the run checks 26.

  5. the move: read the bound

    the line:
    C∈O(n2×n!)C \in O(n^2 \times n!)

    why it is allowed: By line 4, with the fixed multiple 1, as n×n!×nn \times n! \times n is n2×n!n^2 \times n!.

  6. the move: a floor

    the line:
    C≥nC \ge n
    boardfloor, nnCC, countedceiling, n2×n!n^2 \times n!
    2 by 2268
    4 by 4426384
    6 by 6617125,920
    8 by 888762,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.

  7. the move: read the bound

    the line:
    C∈Ω(n)C \in \Omega(n)

    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.

try it with a small nn: no formula gives CC, but at n=4n = 4 the run makes C=26C = 26, which you can count by hand

Question 2: trying every board instead, how many boards, BB, have one queen in each row and each column?
  1. the move: row 1

    the line:
    row 1’s queen hasn squares to choose\begin{gathered} \text{row 1's queen has} \\ n \text{ squares to choose} \end{gathered}

    why it is allowed: No queen is down yet, so any of its nn squares will do. For 4 by 4, a1, b1, c1 or d1.

  2. the move: the rows below

    the line:
    each row below has onecolumn fewer to choose\begin{gathered} \text{each row below has one} \\ \text{column fewer to choose} \end{gathered}
    row 1row 2row 3
    a1b2c3
    a1c2b3
    b1a2c3
    b1c2a3
    c1a2b3
    c1b2a3
    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.

  3. the move: multiply them

    the line:
    B=n!B = n!

    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: n!n!. For 8 by 8, 40,320 boards, before any diagonal is looked at. The method checks 876 squares there.

try it with a small nn: at n=4n = 4, line 3 gives B=24B = 24, 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.

4, every step written down
stepwhat happenssquares checkedqueens put down
1Put 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.00
2Queen 1 goes on a1, the first square in row 1 that no queen attacks.11
3Queen 2 goes on c2, the first square in row 2 that no queen attacks.42
4Row 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.93
5Queen 3 goes on b3, the first square in row 3 that no queen attacks.114
6Row 4 has no square left to try, and every square further along row 3 from b3 is attacked. So queen 3 comes off.174
7Row 3 has no square left to try, and every square further along row 2 from d2 is attacked. So queen 2 comes off.174
8Row 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.185
9Queen 2 goes on d2, the first square in row 2 that no queen attacks.226
10Queen 3 goes on a3, the first square in row 3 that no queen attacks.237
11Queen 4 goes on c4, the first square in row 4 that no queen attacks.268
12A queen in every row, and no two attack each other: that is an answer for 4 by 4.268

In all, 26 squares checked. No formula gives this count. Section 4 puts it between 4 and 384 at n=4n = 4, 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 n!n! 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.

way8 by 8
every board with one queen a row16,777,216 boards
every board with one queen a row and a column40,320 boards
going back, every answer15,720 squares checked, 92 answers
going back, the first answer876 squares checked
Each row counted by running the way; Wirth's 1971 paper counts the same 876 and 15,720. One queen a row is 8 choices in each of 8 rows, 8 to the power 8 boards.
boardboards, n!n!the method checks
4 by 42426 squares
6 by 6720171 squares
8 by 840,320876 squares
12 by 12479,001,6003,066 squares
Trying every board means n!n! boards, each with its diagonals still to look at. Going back early skips most of them.