Skip to main content
Library homepage
 

Text Color

Text Size

 

Margin Size

 

Font Type

Enable Dyslexic Font
Mathematics LibreTexts

16.4: Depth-first and breadth-first searches

( \newcommand{\kernel}{\mathrm{null}\,}\)

Let G be a graph. Given vertices v,v of G, we might wish to find a path from v to v, if one exists. We can do this by constructing a tree TG.

Algorithm 16.4.1: Depth-first search.

To create a tree T that is a subgraph of a graph G wherein a path (in G) from v to v is evident, begin with T containing the single vertex v and no edges. Set x=v.

  1. Look for a vertex y of G which is adjacent to x but not already in T. If such a y is found, go to Step 2. Otherwise, go to Step 3.
  2. Adjoin y and a single edge between x and y to T. If y=v, stop — a path from v to v exists and is now contained in T. Otherwise, set x=y and return to Step 1.
  3. If you have arrived here immediately after beginning the algorithm (i.e. with x still set to be v), stop — there is no path from v to v. Otherwise, return to the vertex z adjoined before x. Set x=z and return to Step 1.

The depth-first search will not necessarily yield the shortest path from v to v. The following algorithm will.

Algorithm 16.4.2: Breadth-first search.

To create a tree T that is a subgraph of a graph G wherein the shortest path in G from v to v is evident, begin with T containing the single vertex v and no edges.

  1. For each vertex x in T added in the last application of this step (or, in the case of the first application of this step, for x=v), adjoin all vertices of G that are adjacent to x and not already in T, along with a single edge between each such vertex and x. If at least one vertex has been adjoined to T in this step, proceed to Step 2. Otherwise, stop — there is no path from v to v in G.
  2. If v was one of the vertices adjoined in Step 1, stop — a path from v to v exists and is now contained in T. Otherwise, return to Step 1.

This page titled 16.4: Depth-first and breadth-first searches is shared under a GNU Free Documentation License 1.3 license and was authored, remixed, and/or curated by Jeremy Sylvestre via source content that was edited to the style and standards of the LibreTexts platform.

  • Was this article helpful?

Support Center

How can we help?