Search⌘ K
AI Features

Topological Sorting

Explore topological sorting to understand how vertices in directed acyclic graphs (DAGs) are ordered using depth-first search. Learn why this ordering ensures dependencies appear before dependent tasks, and see its application in scheduling processes with prerequisite constraints.

Directed acyclic graphs

A directed acyclic graph (DAG) is a directed graph, with the additional property that it is acyclic, i.e., has no cycles.

Technical Quiz
1.

(True of False) The following digraph is a DAG.

A.

True

B.

False


1 / 4

Topologically sorting vertices of a DAG

A topological sort on the vertex set of a DAG is a sequential arrangement of its vertices so that the tail vertex of each edge appears in that sequence before the head vertex of that edge.

Visually, all the edges look positioned from left to right. The graph below on the left can be topologically sorted, as shown on the right.

A DAG and a topologically sorted ordering of its vertices
A DAG and a topologically sorted ordering of its vertices

Such an order is not unique. In the above example, if v1v_1 was moved to the left of v5v_5, we would get a different topologically sorted ordering of vertices.

Getting depth-first search to sort topologically

Recall how we modified our depth-first search implementation to mark the vertices as explored after all edges on a vertex have been explored. This order, in which the endedended attributes are timestamped, induces a natural topological ordering on the vertices of the graph.

For example, consider the following graph, where v4v_4 serves as the root for the DepthFirstSearch algorithm, and the two timestamps for each vertex ...