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.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    const choices = [_]i64{2, 4, 3};
    var picked = [_]i64{-1, -1};
    var depth: i64 = 0;
    while (depth >= 0) {
        picked[@intCast(depth)] += 1;
        if (picked[@intCast(depth)] >= 3) {
            picked[@intCast(depth)] = -1;
            depth -= 1;
        } else {
            if (depth == 0) {
                depth += 1;
                picked[@intCast(depth)] = picked[0];
            } else {
                if ((choices[@intCast(picked[0])] + choices[@intCast(picked[1])]) == 5) {
                    try show(choices[@intCast(picked[0])]);
                    try show(choices[@intCast(picked[1])]);
                    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.