...

/

Application 1: Topological Sort

Application 1: Topological Sort

Practice applying DFS to compute topological sorts.

In this lesson, we’ll apply the DFS algorithm to solve a task ordering problem.

The topological sorting problem

Our goal is to order a set of tasks in a way that respects the dependencies between them. For example, let’s assume that you’re planning your activities for the day. Unfortunately, there is a collection of household chores that you’ll need to complete first, such as washing the dishes, withdrawing cash, grocery shopping, and cooking. Some of these activities may depend on each other. For instance, you need to shop for groceries before you can cook dinner. And you need to withdraw cash before you can shop for groceries.

These tasks and dependencies can be modeled in a task graph. Each task is a node of the graph, and there is an edge (u,v)(u, v) whenever task vv directly depends on task uu. The following figure shows an example task graph.

g a shop groceries b cook dinner a->b e cook lunch a->e c wash dishes c->b c->e d withdraw cash d->a e->b
An example task graph.

Whenever there is a path uvu \rightarrow v in the task graph, the task vv (directly or indirectly) depends on the task uu. This means that we have to perform task uu ...