liveBook · Manning

Backtracking

As explained in Software Design for Python Programmers

Backtracking is the process of reversing or revising earlier decisions when they lead to an unsatisfactory result.

Backtracking reverses an earlier decision when the current path cannot produce an acceptable result. In software design, it also means revisiting a poor decision as requirements and testing expose its weaknesses. section 2.0 section 15.8

A recursive backtracking search typically proceeds by:

  • Treating each partial decision as a stage with one or more possible next steps. section 15.8
  • Taking one valid path recursively, reducing the remaining problem until reaching a solution or dead end. section 15.11
  • Undoing the latest choice at a dead end, then trying the next available choice. section 15.8
  • Stopping after one solution or continuing to earlier stages to find additional solutions. section 15.8

Solving Sudoku

A solver fills cells from left to right and top to bottom. For each empty cell, it tries numbers from 1 through 9 and accepts a number only when its row, column, and three-by-three block remain valid. It recursively solves the next cell; when no number works there, it resets the previous cell to zero and tries that cell’s next candidate. Reaching the final cell produces a solution. section 15.10

How Software Design for Python Programmers covers it

How deep it goes
Explains stages, paths, base cases, choice reversal, and solution termination, then demonstrates the mechanics in complete Python examples.
Examples
Demonstrates backtracking through the eight queens puzzle, Sudoku solving, decision trees, and evolving a book catalogue design.
What it assumes
Assumes basic data structures, algorithms, Python programming, debugging, and object-oriented programming while developing recursion through examples.
What you can do after
Build recursive searches that test valid choices, undo failed choices, and either find one solution or enumerate all solutions.
How it connects
Connects backtracking with recursion, brute-force search, design principles, and iterative software development.

Also explained in

Compare how 6 books explain backtracking →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Design for Python Programmers. The section links point to the parts of the book it draws on.