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
lesson.jl
function main()
    choices = [2, 4, 3]
    picked = [-1, -1]
    depth = 0
    while depth >= 0
        picked[1 + depth] += 1
        if picked[1 + depth] >= 3
            picked[1 + depth] = -1
            depth -= 1
        else
            if depth == 0
                depth += 1
                picked[1 + depth] = picked[1 + 0]
            else
                if (choices[1 + picked[1 + 0]] + choices[1 + picked[1 + 1]]) == 5
                    println(choices[1 + picked[1 + 0]])
                    println(choices[1 + picked[1 + 1]])
                    break
                end
            end
        end
    end
end

main()
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.