Graphs · Exercise 46 of 100
Depth-first search on a graph
Depth-first search marks a vertex when it first arrives, then follows one unvisited neighbor at a time. When a vertex has no unvisited neighbors left, the search returns to the previous vertex to try another branch.
Try it yourself
An undirected graph has edges AB, AC, BD, DE and CF. Start recursive DFS at A and always choose the alphabetically earliest unvisited neighbor. Which vertex is visited fifth?
One-step hint
Number a vertex on first arrival. Follow the earliest unused neighbor as far as possible, then backtrack without numbering a vertex twice.
Worked solution
- From A choose B before C. The search follows B to D and D to E, visiting A, B, D and E in that order.
- Backtrack through D and B to A because those branches are exhausted. A's next unvisited neighbor is C, the fifth vertex.