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.php
<?php
$choices = [2, 4, 3];
$picked = [-1, -1];
$depth = 0;
while ($depth >= 0) {
    $picked[$depth] += 1;
    if ($picked[$depth] >= 3) {
        $picked[$depth] = -1;
        $depth -= 1;
    } else {
        if ($depth == 0) {
            $depth += 1;
            $picked[$depth] = $picked[0];
        } else {
            if (($choices[$picked[0]] + $choices[$picked[1]]) == 5) {
                echo $choices[$picked[0]], PHP_EOL;
                echo $choices[$picked[1]], PHP_EOL;
                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.