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
  1. Trace a fork
  2. Keep the visited rule
  3. Inspect enter and leave events on a branch
  4. Preserve what the recursive procedure does if translating it

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.

References

  1. Eric Lehman, F. Thomson Leighton and Albert R. Meyer, Mathematics for Computer Science ↩