Lesson contents

Depth-first search

Depth-first search follows one branch before trying another. A stack or the program’s call stack remembers where to return.

Simple example

Follow the lower-numbered neighbour first. Visit 1, then 2 and 4. Return to 1 before visiting 3.

Start1→2,3 2→4
Result1 2 4 3
main.rs
fn main() {
    let offsets: [i64; 5] = [0, 2, 3, 3, 3];
    let edges: [i64; 3] = [1, 2, 3];
    let mut seen: [i64; 4] = [0, 0, 0, 0];
    let mut stack: [i64; 4] = [0, 0, 0, 0];
    let mut size: i64 = 1;
    while size > 0 {
        size -= 1;
        let room: i64 = stack[(size) as usize];
        if seen[(room) as usize] == 0 {
            seen[(room) as usize] = 1;
            println!("{}", (room + 1));
            let mut i: i64 = (offsets[((room + 1)) as usize] - 1);
            while i >= offsets[(room) as usize] {
                stack[(size) as usize] = edges[(i) as usize];
                size += 1;
                i -= 1;
            }
        }
    }
}
Output
1
2
4
3
Advertisements

Everyday examples

Inspect nested folders

Folder A has children B and C. B contains D. Finish the B branch before opening C. What order do you see?

StartA→B,C B→D
ResultA B D C

Visit A, enter B, inspect D, then return to A and open C.

Explore a dead end

A trail from P reaches Q, where the path ends. Another branch from P reaches R. Where do you return after Q?

StartP→Q,R
ResultP R

The saved path takes you back to P. You can now explore R instead of restarting the walk.

Avoid following a circle forever

A recommends B, B recommends C, and C recommends A. How many distinct people can you visit?

StartA→B→C→A
Result3

Record each person on first visit. The last link reaches an already visited person, so the branch stops.

Cost and limits

Visit each vertex once. An explicit stack avoids a deep chain of function calls. The visit order can change when neighbours are stored in a different order.