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:
- Push the start vertex onto the stack.
- Pop a vertex. If it was already visited, skip it. Otherwise mark it visited and record it in the visit order.
- Push its unvisited neighbors. To visit them in ascending order, push them from largest to smallest so the smallest is popped first.
- 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.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Depth-First Search - Graph Algorithms
2The Algorithm
How it works?Pseudo CodeImplementation (Part 1)Implementation (Part 2)