Depth First Search (DFS)

About

Is a Graph or Tree traversal algorithm used to explore nodes and edges. It can also be used as a Search algorithm.

Preserves the shape of the traversal.

It uses Stack to store nodes in order.

How it Works

DFS explores entire branches (goes all the way to the leafs) first before moving to neighbor branches.

Drawing

In more detail

circle-exclamation
circle-check
  1. At start node N:

    1. Push N to the Stack.

    2. Push N's children to the Stack.

    3. Process N and remove it from the Stack.

  2. Pop next node N (last) from Stack:

    1. Push its children to the Stack.

    2. Process node N, and remove it from Stack.

  3. Repeat 2. until all nodes were processed.

Last updated