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.
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 offsets = [_]i64{0, 2, 3, 3, 3};
const edges = [_]i64{1, 2, 3};
var seen = [_]i64{0, 0, 0, 0};
var stack = [_]i64{0, 0, 0, 0};
var size: i64 = 1;
while (size > 0) {
size -= 1;
const room: i64 = stack[@intCast(size)];
if (seen[@intCast(room)] == 0) {
seen[@intCast(room)] = 1;
try show((room + 1));
var i: i64 = (offsets[@intCast((room + 1))] - 1);
while (i >= offsets[@intCast(room)]) {
stack[@intCast(size)] = edges[@intCast(i)];
size += 1;
i -= 1;
}
}
}
}
1 2 4 3
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?
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?
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?
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.