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)→1queens(4)→2Now 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 - colorrow + colis 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
- Every row must have exactly one queen, so go row by row and choose a column.
- A square is attacked if its column, its
row - coldiagonal or itsrow + coldiagonal is already taken. - Skip attacked columns. Otherwise add to
cols,d1,d2, callplace(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 waysWhere 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.