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.
def main():
var offsets: List[Int] = [0, 2, 3, 3, 3]
var edges: List[Int] = [1, 2, 3]
var seen: List[Int] = [0, 0, 0, 0]
var stack: List[Int] = [0, 0, 0, 0]
var size = 1
while size > 0:
size -= 1
var room = stack[size]
if seen[room] == 0:
seen[room] = 1
print((room + 1))
var i = (offsets[(room + 1)] - 1)
while i >= offsets[room]:
stack[size] = edges[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.