Topological Sort
Get to know the topological sort problem and its solution using depth-first search.
We'll cover the following...
Topological ordering and postordering in directed graphs
A topological ordering of a directed graph is a total order (The symbol represents a partial order or a strict order relation between elements.) on the vertices such that for every edge . Less formally, a topological ordering arranges the vertices along a horizontal line so that all edges point from left to right. A topological ordering is clearly impossible if graph has a directed cycle—the rightmost vertex of the cycle would have an edge pointing to the left!
On the other hand, consider an arbitrary postordering of an arbitrary directed graph . Our earlier analysis implies that for any edge , and contains a directed path from to , therefore also containing a directed cycle through . Equivalently, if is acyclic, then for every edge . It follows that every directed acyclic graph has a topological ordering; in particular, the reversal of any postordering of is a topological ordering of .
If we require the topological ordering in a separate data structure, we can simply write the vertices into an array in reverse postorder in time, as shown in the algorithm below.
Implicit topological sort
But recording the topological order into a separate data structure is usually overkill. In most applications of the topological sort, the ordered list of the vertices is not our actual goal; rather, we want to perform some fixed computation at each vertex of the graph, either in topological order or in reverse topological order. For these applications, it is not necessary to record the topological order at all!
Algorithm
...
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy