Search⌘ K
AI Features

Whatever-First Search

Explore the Whatever-First Search algorithm, a general framework for graph traversal that includes depth-first search as a special case. Understand how to implement recursive and iterative DFS, how reachability is determined, and how the algorithm builds spanning trees in undirected graphs. This lesson equips you with the concepts and coding skills to traverse graphs efficiently in C++.

Depth-first search

So far, we have only discussed local operations on graphs; arguably, the most fundamental global question we can ask about graphs is reachability. Given a graph GG and a vertex ss in GG, the reachability question asks which vertices are reachable from ss; that is, for which vertices vv is there a path from ss to vv? For now, let’s consider only undirected graphs; we’ll consider directed graphs briefly at the end of this section. For undirected graphs, the vertices reachable from ss are precisely the vertices in the same component as ss.

Perhaps the most natural reachability algorithm—at least for people like us who are used to thinking recursively—is depth-first search. This algorithm can be written either recursively or iteratively. It’s exactly the same algorithm either way; the only difference is that we can actually see the “recursion” stack in the non-recursive version.

Algorithm


RecursiveDFS(v):if v is unmarkedmark vfor each edge vwRecursiveDFS(w)\underline{RecursiveDFS(v):} \\ \hspace{0.4cm} if\space v\space is\space unmarked \\ \hspace{1cm} mark\space v \\ \hspace{1.0cm} for\space each\space edge\space vw \\ \hspace{1.7cm} RecursiveDFS(w)

IterativeDFS(s):Push(s)while the stack is not emptyvPopif v is unmarkedmark vfor each edge vwPush(w)\underline{IterativeDFS(s):} \\ \hspace{0.4cm} Push(s) \\ \hspace{0.4cm} while\space the\space stack\space is\space not\space empty \\ \hspace{1.0cm} v ← Pop \\ \hspace{1cm} if\space v\space is\space unmarked \\ \hspace{1.7cm} mark\space v \\ \hspace{1.7cm} for\space each\space edge\space vw \\ \hspace{2.3cm} Push(w) ...