Count the ways to place n queens with no attacks: one queen per row, three sets for columns and diagonals, undo and try the next.
▼The problem
LeetCode 52 (Hard). Given n, return the number of distinct ways to place n queens on an n × n board so that no two queens attack each other (same row, column or diagonal). Only the count is returned, no boards.
Examples (LeetCode's): n = 4 → 2 and n = 1 → 1.
The solution
def totalNQueens(n):
cols, diag, anti = set(), set(), set()
def place(r):
if r == n:
return 1 # every row filled
count = 0
for c in range(n):
if c in cols or r - c in diag or r + c in anti:
continue
cols.add(c); diag.add(r - c); anti.add(r + c)
count += place(r + 1)
cols.remove(c); diag.remove(r - c); anti.remove(r + c)
return count
return place(0)Transcript
N-Queens Two. Place n queens on an n by n board so that no two attack each other: no shared row, column or diagonal. This time, don't build the boards. Just count them.
Four queens fit in exactly two ways, and they're mirror images. One queen fits in one way. Two and three queens have none, and then the counts jump: ten for five, forty for seven, ninety-two for eight.
The naive way puts one queen in each row, in every possible column, and checks each board at the end. That's n to the n boards: two hundred fifty-six for four, and over sixteen million for eight.
Better: place queens row by row, and only on safe squares. One queen per row takes care of the rows. For the rest, keep three sets: used columns, diagonals and anti-diagonals. Along a diagonal, row minus column stays the same. Along an anti-diagonal, row plus column does. So every square costs three constant-time lookups.
If a row has no safe square, back up right away: lift the queen above it and try her next column. Fill all n rows, and that's one more way.
Let's count four. Starting in the corner, both tries below it dead-end, so back up. Column two works all the way down: one. Column three mirrors it: two. Column four dead-ends. Total: two.
In code, each call fills one row and returns how many boards it completes. Past the last row, return one. Otherwise, for each column missing from all three sets, add it, add up the next row's count, then remove it. For more speed, the sets can be bitmasks.
The first row has n columns to try, the next at most n minus one, and so on, so time grows roughly like n factorial. Even so, eight queens takes just two thousand fifty-six placements. Space is order n: the sets and the recursion.
One queen per row, three sets, add one at the bottom. That's N-Queens Two.