The puzzle
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.
One queen per row means a list says it all: cols[r] is the column of the queen in row r. Trying every list blindly means 4⁴ = 256 full boards. Backtracking builds the list one row at a time instead.
Search and prune
place(0) works on row 0. The board is empty, so safe(0, 0) is true and cols[0] = 0. The squares this queen attacks in the rows below are shaded: its column and its diagonal.
place(1) tries row 1. Column 0 shares a column with the first queen, column 1 a diagonal, so safe() says no and the loop skips them without going deeper. That skip is pruning. Column 2 is safe: cols[1] = 2.
Row 2: all four squares are attacked. safe() fails four times, the loop runs out and place(2) returns False. No board that starts with queens at columns 0 and 2 is ever built past this row.
Backtrack: control returns to place(1), whose loop simply moves on. Column 3 is safe, so cols[1] = 3 overwrites the 2. Row 2 now has a safe square at column 1: cols[2] = 1.
Row 3 is fully attacked: dead end. Back in row 2, columns 2 and 3 fail too. Row 1 has no columns left. So no solution starts with a queen in column 0 of row 0.
Back at the top, place(0) moves its queen to column 1. Row 1 rejects columns 0, 1 and 2, and takes column 3.
Why pruning pays
Row 2 takes column 0, row 3 takes column 2, and place(4) finds r == N: solved, cols = [1, 3, 0, 2]. That took 26 safe() checks. Trying full boards in order would reach this one only at board 115.
Pruning pays more as boards grow. 8 queens have 8⁸ = 16,777,216 one-per-row boards. Backtracking finds all 92 solutions after 15,720 safe() checks, because each dead branch is cut the moment its first queen fails.
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.