N-Queens
Constraint search through place, prune, and backtrack
Place one queen in every column
The N-Queens problem asks for N queens on an N x N board with no two sharing a row, column, or diagonal. Placing exactly one queen per column removes the column constraint and turns each recursive level into a choice of row.
Reject conflicts before recursing
Try rows from top to bottom in the current column. A square is safe when no earlier queen shares its row or diagonal. Place a queen and recurse when safe; if later columns become impossible, remove that queen and continue with the next row.
Amber marks the square under consideration, red identifies queens that attack a rejected square, and placed queens remain on the board. The trace stops after finding one solution for the 4 by 4 instance.
Start with an empty board and place one queen in each column from left to right.
Search cost depends on pruning
The worst-case search is commonly bounded by O(N!) after enforcing one queen per row and column, with O(N) recursion depth. Constant-time row and diagonal sets make conflict checks faster for larger boards.
See the same depth-first choose-and-undo pattern without constraints in Subsets.