Backtracking and Choice Points

Backtracking tries a choice, explores its consequences, and restores the state needed to try another choice.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a two-step choice
  2. Use copies intentionally
  3. Restore only state the failed choice introduced
  4. Watch how successful results keep their data

Trace a two-step choice

Choosing one of A or B and then one of 1 or 2 yields A1, A2, B1, and B2. After emitting A1, remove the last choice before appending 2. Recursive call tracing helps show which completed choice each frame leaves behind.

Use copies intentionally

If the partial solution is shared and mutable, adding that same object to the results can make all stored answers reflect the last edits. Store a snapshot at completion. Shallow container copies explain when a copy suffices.[1]

Restore only state the failed choice introduced

Consider assigning distinct badge colors to three seats. Seat one can take red or blue. Seat two permits red only. First choosing red for seat one leaves seat two with no legal choice, so remove red from the used set and resume the earlier decision. See pruning impossible branches.

Seat one = red   → seat two impossible → undo red
Seat one = blue  → seat two = red      → seat three = green
One feasible assignment: blue, red, green

Watch how successful results keep their data

If the algorithm saves the current assignment by reference and backtracks over it, later removals can empty the saved result. Store a snapshot at the solution point. Test an initial failure followed by success and a problem with no feasible assignment.

References

  1. Jeff Erickson, Algorithms ↩