IT lexicon Programming DFS (Depth-First Search)

DFS (Depth-First Search)

Programming På svenska → Updated: 2026-05-23

Graph traversal that goes as deep as possible before backtracking — implemented with a stack (or recursion).

Three colours for cycle detection: white (unseen), grey (in progress, sibling on the recursion stack), black (done). A grey-to-grey edge = a cycle. Required for topological sort, connectivity detection (Tarjan), maze generation.

Time complexity O(V+E). Worst-case space O(V) (deep recursion). Competitor: BFS (FIFO instead of stack, finds shortest unweighted path). Iterative DFS recommended for deep graphs to avoid stack overflow.

← Back to the lexicon