Problem Solving

Depth-First Search

A student traces a long branching route before returning to a junction.

Depth-First Search definition

Depth-first search explores one branch of a graph as far as possible before backtracking.

In Spanish
búsqueda en profundidad
Topic
Graph algorithms and networks

Depth-First Search in a picture

Depth-First Search diagramStarting from A, search can go to B and then D before returning to explore C.Begin at AMark A as visitedFollow the branch A–B–DContinue while an unvisited neighbor existsBacktrack to AThen explore the remaining neighbor C
Starting from A, search can go to B and then D before returning to explore C.

How it works

Mark each vertex when it is first reached. Recursively explore an unvisited neighbor, or use an explicit stack to manage the branch. When no unvisited neighbor remains, return to the previous vertex and continue from there.

Worked examples

What structure supports the search without recursion?

An explicit last-in, first-out stack or stack of traversal frames.

What if a vertex has only visited neighbors?

Backtrack.

Does depth-first search guarantee a shortest path in an unweighted graph?

No. It may discover a longer branch first.

Common mistake

Track visited vertices to avoid looping around cycles.

Quick check

When does the search backtrack?

Can neighbor order change the visitation order?

Show answer

Yes.

Which graph search visits by distance layers?

Show answer

Breadth-first search.

Sources

Flashcard

Depth-First Search

Reveal the definition

Depth-first search explores one branch of a graph as far as possible before backtracking.

Effortless Math. “Depth-First Search.” Math Dictionary.