Lesson contents

Backtracking and undoing a choice

Try one option. If it cannot finish the job, undo that choice and try another. Keep the choices that lead to a solution.

Simple example

Choose two different numbers from 2, 4 and 3 that add to 5. The first trial, 2 and 4, misses. Replace 4 with 3 and print the pair.

Start2 + ? = 5
Result2 3
main.rs
fn main() {
    let choices: [i64; 3] = [2, 4, 3];
    let mut picked: [i64; 2] = [-1, -1];
    let mut depth: i64 = 0;
    while depth >= 0 {
        picked[(depth) as usize] += 1;
        if picked[(depth) as usize] >= 3 {
            picked[(depth) as usize] = -1;
            depth -= 1;
        } else {
            if depth == 0 {
                depth += 1;
                picked[(depth) as usize] = picked[0];
            } else {
                if (choices[(picked[0]) as usize] + choices[(picked[1]) as usize]) == 5 {
                    println!("{}", choices[(picked[0]) as usize]);
                    println!("{}", choices[(picked[1]) as usize]);
                    break;
                }
            }
        }
    }
}
Output
2
3
Advertisements

Everyday examples

Leave a dead end

At a fork the left path ends at a wall. The right path reaches the exit. Where do you resume the search?

StartA→B ×
ResultA→C ✓

Return to the fork. Keep track of the failed branch so you do not enter it again.

Pick two distinct time slots

You need three hours. Available slots last 2, 2 and 1 hours. Which second choice works with the first slot?

Start2+2 / 2+1
Result2+1

Undo the second two-hour booking. Try the one-hour booking instead.

Place two tokens on a board

A token already occupies the only square in one row. Can a second token go there if each row allows one?

StartA→1
ResultB→2

Reject the occupied row before exploring later placements. Try an unused row.

Cost and limits

Backtracking can try exponentially many choices. Reject a branch early only when you can prove that it cannot lead to a solution.