A Depth-First Search by Hand
Depth-first search follows one path as far as it can before returning to explore unfinished alternatives.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a fork
From A, visit first neighbor B, then B's new neighbor D. When D has no further work, return to B and then A to examine C. A stack can retain which suspended choices need attention.
Keep the visited rule
An undirected edge from D back to B should not restart B's entire exploration. Mark before expanding a new vertex. Compare depth-first search for how entry and exit observations support additional graph queries.[1]
Inspect enter and leave events on a branch
With directed edges A→B, A→C, B→D and D→C, choose B before C at A. The search walks down B and D to C before leaving any ancestor. Its depth-first tree includes parent of C equal to D. See preorder and postorder traces.
Enter: A, B, D, C
Leave: C, D, B, A
Edge A→C sees an already visited C when considered later
Preserve what the recursive procedure does if translating it
Pushing every neighbor onto a stack all at once can change when vertices are marked and which edges become tree edges. To reproduce recursive entry and exit precisely, carry a neighbor cursor per frame. Test a graph where two branches can reach the same vertex.