šŸ“˜ CodingMarble Learn

Backtracking

Backtracking builds an answer one choice at a time. If a choice breaks a rule, it is cut (pruned); when a branch is finished or stuck, the program goes back one step and tries the next choice. It is used to generate all Cartesian products, permutations, arrangements, combinations and subsets.

šŸŽ¬ Step-by-step story

  1. Goal: put 1, 2, 3 in three slots in every possible order. Each slot needs one digit. The slots are empty and the tree has only its start.
  2. First choice: put 1 in slot 1. One step down the tree.
  3. Try 1 in slot 2 again: not allowed! The digit 1 is already used. The red cross means this branch is cut (pruning).
  4. Now place 2, then 3. All slots are full: the first answer 1 2 3 is found (green).
  5. Backtrack: remove 3, remove 2, try the next choice 3 in slot 2, then 2. The second answer: 1 3 2.
  6. Free play: press "Next step" or "Auto". The tree grows until all 6 answers are found.

Tip: drag the 3D scene to turn it. Use two fingers to zoom.

šŸ¤” Common doubts, cleared

What does the red cross mean?

That choice breaks the rule (the digit is already used), so the branch is cut. See step 2.

What is the tree?

It is a picture of all choices tried so far. Each level is one more slot. The tree grows as we explore.

When is an answer complete?

When all three slots are full. The last node turns green in step 3.

What exactly is going back?

We remove the last digit and try the next option for that slot. Watch the slots empty in step 4.

Why not list everything and check at the end?

That wastes time on answers that already broke a rule. Cutting early saves tries.

How do I run the whole thing?

Use Next step, or Auto. It ends after all 6 answers.

The general idea

Backtracking builds a solution step by step. At each step you choose one option, check the rules, and go deeper. If the rules fail, or you reach a dead end, you go back (undo) the last choice and try another one.

All the tries make a tree: the top is the empty answer, each level is one more choice. Backtracking walks this tree depth first. A cut branch saves a lot of work. The method uses recursion: each level is one call.

solve(k):            // fill slot k
  for each option v:
    if v is allowed at slot k:
      x[k] = v
      if k is the last slot: print x
      else solve(k + 1)
    // loop continues = go back and try next v

Cartesian product

The Cartesian product of sets A and B is every pair (a, b). Backtracking: slot 1 takes each value of A; for each, slot 2 takes each value of B. Every option is allowed, so nothing is cut.

For A = {1, 2} and B = {x, y, z} we get 2 Ɨ 3 = 6 pairs: (1,x) (1,y) (1,z) (2,x) (2,y) (2,z).

Permutations

A permutation of n items uses all n items once, in every order. Rule: a value is allowed only if it is not already used. That is the rule that cuts the red branches in the 3D.

There are n! permutations: 3 items give 3! = 6 (123, 132, 213, 231, 312, 321), 4 items give 24.

Arrangements

An arrangement of n items taken k at a time is an ordered list of k different items. Same code as permutations, but the answer is complete after k slots, not n.

Count: A(n, k) = n! / (n āˆ’ k)!. For n = 5, k = 2: 5 Ɨ 4 = 20.

Combinations

A combination of n items taken k at a time is a group of k items where order does not matter. To avoid repeats, force the values to increase: x[k] must be bigger than x[k āˆ’ 1]. That cuts all repeated orders.

Count: C(n, k) = n! / (k! (n āˆ’ k)!). For n = 4, k = 2: (1,2) (1,3) (1,4) (2,3) (2,4) (3,4), which is 6.

Subsets

A subset picks any items of a set, possibly none. Backtracking: for each item decide "take" or "leave". That is 2 choices per item, so a set of n items has 2ⁿ subsets. For {a, b, c} there are 8.

Try it

Take three coloured pencils and list all the orders on paper. Do it by backtracking: fix the first pencil, list the rest, then go back and change the first. In the 3D, before pressing Next step, guess whether the next move is a place, a rejection, or a step back.

Key formulas and definitions

Worked examples

1. List all permutations of {1, 2, 3} in the order the backtracking finds them.

1 2 3, 1 3 2, 2 1 3, 2 3 1, 3 1 2, 3 2 1. That is 3! = 6.

2. How many permutations of 4 different digits?

4! = 4 Ɨ 3 Ɨ 2 Ɨ 1 = 24.

3. How many arrangements of 5 letters taken 2 at a time?

A(5, 2) = 5 Ɨ 4 = 20.

4. List all combinations of {1, 2, 3, 4} taken 2 at a time.

Keep values increasing: (1,2) (1,3) (1,4) (2,3) (2,4) (3,4). That is 6 = C(4, 2).

5. List all subsets of {a, b, c}.

For each item take or leave: {}, {a}, {b}, {c}, {a,b}, {a,c}, {b,c}, {a,b,c}. That is 2³ = 8.

6. While building permutations of 1, 2, 3, how many times is a digit rejected as already used?

Under each first digit there are 5 rejections: 1 at slot 2, and 2 at slot 3 in each of the two sub-branches. So 5 Ɨ 3 = 15 rejections in all. You can count them as you press Next step in the 3D.

Common mistakes

Practice quiz

1. Backtracking means:
2. How many permutations does {1, 2, 3, 4} have?
3. To avoid repeated digits in a permutation we:
4. Subsets of a set with 4 items:
5. In combinations we force the values to be:

Practice: answer these yourself

Type or choose your answer, then press Check. Use a hint if you are stuck; the full solution appears after you answer.

Frequently asked questions

What is the difference between backtracking and recursion?

Recursion is the tool (a function that calls itself). Backtracking is the plan: choose, check, go deeper, and undo when stuck. It is usually written with recursion.

Why is backtracking called depth-first?

It goes as deep as it can along one branch before coming back. In the 3D the walker goes down to a full answer first.

Is backtracking always slow?

The tree can be huge (n! grows very fast). Cutting branches early with the rules makes it much faster. For large n, other methods may be needed.

Learn first

Learn next

Related lessons

All Computer Science lessons