Solution: Topological Sorting of a Graph
This review provides a detailed analysis of the solution to perform topological sorting of a graph.
We'll cover the following...
Solution #1: Using Graph Traversal
We can modify graph traversal algorithms to find Topological Sorting of a graph.
While traversing a graph, we start from a vertex. First, print it and then recursively call the utility function for its adjacent vertices.
In topological sorting, we use a temporary stack. We do not print the vertex immediately; before that, we recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack.
Note: A vertex is pushed to stack only when all of its adjacent vertices are already in the stack.
Pseudocode
function utilityFunction(v)
mark v visited
for each node i with an edge from v to i
utilityFunction(i)
add v to head to myStack
function topologicalSort()
myStack ← Empty list that will contain the sorted
nodes
while there are unvisited nodes do
select an unvisited node i
utilityFunction(i)
print myStack
The pseudocode is mapped in the solution above.
Time Complexity
The above algorithm is a modified version of DFS with an extra stack, so time complexity is the same as DFS with .