012301231def place(r):2 if r == N:3 return True4 for c in range(N):5 if safe(r, c):6 cols[r] = c7 if place(r + 1):8 return True9 return Falsechecks0placed0cols[0]·cols[1]·cols[2]·cols[3]·
Queens: one per row, sliding along the row as place(r) tries each columnShaded squares: attacked by a queen above · cross: safe() said no, skippedBoxes: the list cols and the two countersThe recursive function place(r) puts one queen in row r. Each square it tries costs one safe() check. A cross means safe() said no, so nothing below that square is built (pruning). A row with no safe square sends control back to the row above (backtracking). The search ends at cols = [1, 3, 0, 2] after 26 checks.

The puzzle

  1. Put 4 queens on a 4×4 board so that no two attack each other. A queen attacks along its row, its column and both diagonals. So every row must hold exactly one queen. On an 8×8 board this is the eight queens puzzle.

Search and prune

Why pruning pays

What happens

;; step 1/10 · the-puzzle
goal: 4 queens on a 4×4 board, no two in the same
  row, column or diagonal

solutions for N = 4: 2   (for N = 8: 92)

Cells for rows below the current row show a dot. In the real list they still hold old values, but safe() never reads them: it only looks at rows 0 to r − 1. "Board 115": listing every one-per-row board in order, [0,0,0,0], [0,0,0,1], ..., the solution [1, 3, 0, 2] comes at position 1·64 + 3·16 + 0·4 + 2 + 1 = 115, and each of those boards would need a full check.