Menu
Coddy logo textTech

How it works?

Lesson 3 of 9 in Coddy's Depth-First Search - Graph Algorithms course.

DFS keeps a visited marker for each vertex and a stack of vertices to process.

Step-by-Step Process:

  1. Push the start vertex onto the stack.
  2. Pop a vertex. If it was already visited, skip it. Otherwise mark it visited and record it in the visit order.
  3. Push its unvisited neighbors. To visit them in ascending order, push them from largest to smallest so the smallest is popped first.
  4. Repeat until the stack is empty.

Example on vertices 0..3 with edges [0,1, 0,2, 1,3, 2,3], starting at 0:

  • Visit 0, then its smallest neighbor 1, then 1's neighbor 3, then 3's neighbor 2.
  • Visit order: [0, 1, 3, 2].

Only vertices reachable from the start are visited.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Depth-First Search - Graph Algorithms