Algorithms · Backtracking

N-Queens

Place n queens so none attack each other.

The problem

Place n chess queens on an n×n board so that no two share a row, a column or a diagonal. Return how many ways there are.

queens(1)1
queens(4)2
Backtracking. Try, undo, try again. A maze: walk until you hit a dead end, step back, try the next turn.

Now ask: what if there were a billion?

Chip designers, timetable makers and airline schedulers face puzzles like this with thousands of pieces. Trying everything is hopeless, so they use SAT solvers: backtracking with very clever pruning.

Aim for O(n!)🔥 boss

Think it through

How many queens can each row hold?

  • Exactly one
  • Up to two
Show the answer

Exactly one. Two in a row attack each other, and n queens fill n rows, so it’s one per row. Go row by row and choose a column.

How do you know a square is on an attacked diagonal, without walking the diagonal?

  • row - col or row + col is already taken
  • Check every queen placed so far
Show the answer

row - col or row + col is already taken. Every square on one diagonal shares row - col; on the other, row + col. Keep three sets (columns, both diagonals) and checking is instant.

Stuck? 3 nudges, smallest first
  1. Every row must have exactly one queen, so go row by row and choose a column.
  2. A square is attacked if its column, its row - col diagonal or its row + col diagonal is already taken.
  3. Skip attacked columns. Otherwise add to cols, d1, d2, call place(row + 1), then remove them again.

The fast way

Try it yourself before you open this.

Show the fast version
def queens(n):take the board size
count = 0solutions found
cols, d1, d2 = set(), set(), set()columns and diagonals already under attack
def place(row):put a queen somewhere in this row
nonlocal countwe'll update the outer count
if row == n:every row has a queen
count += 1one more solution
returngo back and try other spots
for col in range(n):try each column in this row
if col in cols or row - col in d1 or row + col in d2:under attack?
continueskip this square
cols.add(col); d1.add(row - col); d2.add(row + col)place the queen: mark what it attacks
place(row + 1)fill the rows below
cols.remove(col); d1.remove(row - col); d2.remove(row + col)pick the queen back up
place(0)start at the top row
return counthow many ways

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with backtracking