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
lesson.cpp
#include <iostream>

int main() {
    int offsets[] = {0, 2, 3, 3, 3};
    int edges[] = {1, 2, 3};
    int seen[] = {0, 0, 0, 0};
    int stack[] = {0, 0, 0, 0};
    int size = 1;
    while (size > 0) {
        size -= 1;
        int room = stack[size];
        if (seen[room] == 0) {
            seen[room] = 1;
            std::cout << room + 1 << '\n';
            int i = offsets[room + 1] - 1;
            while (i >= offsets[room]) {
                stack[size] = edges[i];
                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.