Graph Search


According to the Dictionary of Algorithms and Data Structures:

Depth-First Search, or DFS, is any search algorithm that considers outgoing edges (children) of a vertex before any of the vertex’s siblings, that is, outgoing edges of the vertex’s predecessor in the search. Extremes are searched first.

The main idea behind DFS is to explore deeper into the graph whenever possible. Starting at a vertex, DFS will take a path and explore it as far as it goes. It then backtracks until it reaches an unexplored neighbor (a branch on the path which it has not explored yet). This process continues until it has discovered every vertex that are reachable from the original source vertex.

You have seen this behavior in pre-order and post-order tree traversal (and in-order binary tree traversal).

The process is further elaborated using a demo:


The following animated visualization of DFS algorithm (made by Gerry Jenkins) does a good job of illustrating its behavior: