Graphs · Exercise 52 of 100
Topological ordering with DFS
In a directed acyclic graph, depth-first search can build a topological ordering by recording each vertex after exploring all its outgoing edges. After visiting every vertex, reverse the recorded list so that each vertex comes before the vertices it points to.
Try it yourself
The arrows are Chop to Cook, Heat to Cook and Cook to Eat. Run recursive DFS starting at Chop, then visit Heat, skipping any vertex already visited. Which task is second in the reversed list of finishing times?
One-step hint
Append a task when its recursive call returns. Keep that list when you start from Heat, then read it from the end.
Worked solution
- Starting at Chop takes the search through Cook to Eat. As it returns, the tasks finish in the order Eat, Cook, Chop.
- Heat finishes last because Cook has already been visited. Reversing the list gives Heat, Chop, Cook, Eat, so Chop is second.