Learn / Recursion and backtracking

N-Queens

Place one queen per row. For each row, try every column that no earlier queen attacks, recurse into the next row, and undo. Three boolean arrays (columns, the r + c diagonals and the r - c diagonals) check a square in O(1).

How to recognise it

  • Items must be placed on a board so that no two clash, one per row or column.
  • The question asks for all valid arrangements or how many there are.

The idea in one picture

Go down the board row by row. In each row, slide a queen along until it sits on a square no earlier queen can reach. Go to the next row. If a row has no safe square, step back to the previous row and slide that queen further.

Checking a square in O(1)

LineSame value along itArray size
columncn
down-right diagonalr - c (shift by n to keep it positive)2n
up-right diagonalr + c2n

Template

function place(r):
    if r == n: record the board; return
    for c from 0 to n - 1:
        if col[c] or diag[r + c] or anti[r - c + n]: continue
        mark all three; queen[r] = c
        place(r + 1)
        unmark all three

Common mistakes

  • Checking only columns, or only one diagonal.
  • Forgetting to unmark after the recursive call.
  • Scanning the whole board to check a square, which is O(n) per check instead of O(1).

Problems

0 of 1 solved

Check yourself

Two squares (r1, c1) and (r2, c2) are on the same up-right diagonal exactly when...

Why place exactly one queen per row?

How many solutions does the 4-queens puzzle have?