Python 3D Academyবাংলা

Backtracking in Python

Chapter 46: Backtracking

4 short lessons, with 3D animations, quizzes and coding tasks.

The lessons

  1. Choose, explore, undo: finding a way through a maze

    Backtracking builds an answer step by step: at each step it chooses one option, explores everything that follows from it, then undoes the choice so the next option starts from the same place.

  2. Subsets and combinations: choosing toppings

    To list every subset, decide take-or-skip for each item in turn; to list every combination of k items, choose items only to the right of the last one chosen, and stop when you have k.

  3. Permutations: seating guests

    To list every permutation (every order) of the items, fill the positions one at a time with any item not used yet, explore the rest, then undo, so that every order is built exactly once.

  4. Pruning: N-Queens and combination sum

    Prune a branch the moment you can prove that nothing below it can be an answer, so the search never spends time inside it.