N-Queens
Place n queens on a board so that none attack each other
DSA, Hard, Backtracking
Which structure or algorithm, and what does it cost.
Place n queens on an n by n board so that no two queens attack each other. Queens attack along a row, a column or a diagonal. Return every valid board. A board is a list of n strings, one per row, with Q for a queen and . for an empty cell. Sort the boards by the queen's column in row 0, then in row 1, and so on.
Examples
Constraints
- 1 <=
n<= 8.
Your answer must contain
- The method; how a cell is tested against the queens already placed; code; time and memory cost; a hand trace of example 1.
Target Aim to place one queen per row and drop a branch the moment a row has no safe column.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Each row holds exactly one queen, so place them one row at a time. What makes a column unsafe for the next row?
Hint 2 the approach
A new queen is unsafe if its column is taken or if a queen already sits on one of its two diagonals. Find a quick test for each.
Hint 3 the key step
Cells on one diagonal share the same row minus column. Cells on the other share the same row plus column. Keep three sets and undo them when a row fails.
Walkthrough
Full walkthrough brute force to best
Brute force
Put one queen in every row, in any column, which is n^n boards, and check every pair of queens on each. For n = 8 that is 16,777,216 boards, and only 92 of them are valid.
Best method
Place queens one row at a time. Keep three sets: the used columns, the used down diagonals (row minus column) and the used up diagonals (row plus column). In row r, try each column c in order. Skip it if c, r - c or r + c is already in a set. Otherwise add them, go to row r + 1, then remove them. When r equals n, build a board from the chosen columns and record it. A row with no safe column returns at once, so the search cuts a whole branch there. Trying columns in order gives the boards in the required order.
Hand trace
Run on n = 6. Row 0, column 0 is tried first. Every path below it dead-ends, for example columns 0, 2, 4, 1, 3 and then row 5 has no safe column. There are seven dead ends under column 0 and no board. Row 0, column 1: row 1 column 3, row 2 column 0, row 3 column 2, row 4 column 4, and row 5 has no safe column. Back up: row 2 column 5, row 3 column 0, row 4 column 2, row 5 column 4. All six rows are placed, so record the board with columns 1, 3, 5, 0, 2, 4. The search goes on and finds three more boards.
Code
def solve_n_queens(n):
out = []
cols = []
taken_col, taken_down, taken_up = set(), set(), set()
def go(r):
if r == n:
out.append(["." * c + "Q" + "." * (n - c - 1) for c in cols])
return
for c in range(n):
if c in taken_col or r - c in taken_down or r + c in taken_up:
continue
cols.append(c)
taken_col.add(c); taken_down.add(r - c); taken_up.add(r + c)
go(r + 1)
taken_col.remove(c); taken_down.remove(r - c); taken_up.remove(r + c)
cols.pop()
go(0)
return outTime and memory
At most n! full paths, because each row uses a different column, and the checks cut most of them. So time is O(n!) in the worst case, plus O(n^2) to build each recorded board. Extra memory is O(n) for the three sets and the recursion, plus the answer.
Common mistakes
- Checking only the columns and one diagonal direction. Queens attack along both diagonals.
- Not removing the column and the two diagonals from the sets when the call returns. Later rows then see queens that are gone.
- Scanning all n * n cells of the board for each test. Checking only the placed queens, or three sets, is enough.