Skip to content
StackDecode
AI & ML Atlas
Artificial IntelligencealgorithmInteractive simulation

Backtracking Search

Depth-first assignment of variables that undoes a choice as soon as it fails.

The idea

Assign one variable at a time. If an assignment breaks a constraint, back up to the previous choice and try a different value. Because it abandons a whole subtree the moment a conflict appears, it is far smaller than trying every combination.

Watch it run

This is a real computation, not a drawing. Pause, step, change the settings, or try new random data.

WANTQNSWVSAT
  • red
  • green
  • blue
  • being assigned

Plain backtracking: assign regions in order and only notice a clash when a region has no colour left.

1/13

Compare the number of tries between plain backtracking and forward checking.

Step by step

  1. 1Choose an unassigned variable.
  2. 2For each value in its domain, check consistency with the current assignment.
  3. 3If consistent, assign and recurse.
  4. 4If the recursion fails, unassign (backtrack) and try the next value.

Where it is used

Sudoku, N-queens, crosswords, general CSPs.

Watch out for

Without smarter ordering or inference it may repeat the same failure many times (thrashing).

Related