Skip to content

Backtracking

Task: Place four queens on a 4x4 board so none can attack another

00112233CALL STACKplace(0)col 1place(1)col 3place(2)col 0place(3)col 2DECISIONS 31 / 31

What you are watching

The four-queens problem solved by backtracking, in 31 decisions. Rows are filled from the top, taking the first column no earlier queen attacks along a column or a diagonal. When a row has no safe column left, the search does the thing that makes it backtracking rather than plain recursion: it lifts the previous queen back off the board and tries the next column for it instead. That happens three times here, once all the way back to the first row, before the columns 1, 3, 0, 2 are found to work.