Topological Sorting
Solved Problems
Example 1.
The set \(A = \left\{ {2,3,4,6,8,9,12,18} \right\}\) is ordered by the divisibility relation "|". Determine a topological sort of the poset.
Solution.
The Hasse diagram of the partially ordered set \(\left( {A, \mid} \right)\) looks like this:
For topological sorting we can use the usual "less than or equal" relation \(\le\). This relation preserves the ordering defined by divisibility, so if \(a\mid b\) for numbers \(a\) and \(b,\) then \(a \le b.\) As a result, we obtain a topological sort of the poset \(\left( {A, \mid} \right)\) in the form of an ascending number sequence:
We can also build another topological sort for the poset. Using Kahn's method, we identify two minimal elements - \(2\) and \(3.\) Starting, for example, from \(3,\) we remove the elements in the following order: \(3, 9, 2, 6, 18, 4, 12, 8.\) This sequence forms a total order of kind
We can easily make sure that this total order preserves the divisibility ordering in the original set and, hence, is a topological sort of \(\left( {A, \mid} \right):\)
Example 2.
The set of geometric shapes is partially ordered by area. Find a topological sort of the shapes.
Solution.
We assume that the area of a shape \(A\) is less than the area of a shape \(B\) and denote is as \(A \preccurlyeq B,\) if the shape \(A\) is inscribed in shape \(B.\)
We identify the following relations between the given shapes:
Draw the Hasse diagram for the partially ordered set:
A possible topological sort (it can be easily built using Kahn's algorithm) has the following form:
Example 3.
General relativity requires a knowledge of mathematics and physics, which is illustrated by the diagram in Figure \(18.\) Determine an order in which these courses can be taken.
Solution.
First we note that the relation defined by the digraph is antisymmetric and transitive. Assuming, for simplicity, that it is also reflexive, we get a partially ordered set, which can be topologically sorted.
There are two vertices that have no incoming edges - Calculus and Linear Algebra. By applying Kahn's algorithm, we select Calculus and remove it from the digraph. This will be the first course in the sorted output list (aren't we lucky?). Then we repeat the process by successively removing Linear Algebra, ODE, and so on.
One of the possible topological sorts looks like this:
Example 4.
A partially ordered set is given by the digraph shown in Figure \(20.\) Find a topological sort of the graph using \(DFS\) algorithm.
Solution.
We identify \(4\) nodes that have no incoming edges: \(1,2,3\) and \(4.\) For each of these elements, we determine the list of adjacent vertices:
Filter out coinciding elements:
Combine the blocks to get a topological sort: