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.R
offsets <- c(0, 2, 3, 3, 3)
edges <- c(1, 2, 3)
seen <- c(0, 0, 0, 0)
stack <- c(0, 0, 0, 0)
size <- 1
while (size > 0) {
    size <- size - 1
    room <- stack[(size) + 1]
    if (seen[(room) + 1] == 0) {
        seen[(room) + 1] <- 1
        cat(room + 1, "\n", sep = "")
        i <- offsets[(room + 1) + 1] - 1
        while (i >= offsets[(room) + 1]) {
            stack[(size) + 1] <- edges[(i) + 1]
            size <- size + 1
            i <- 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.