A topological sorting of a directed graph G is a linear ordering of its vertices such that for every directed edge u->v, u comes before v in the ordering. A topological sorting is possible if and only if the graph has no directed cycles i.e., it is a Directed Acyclic Graph (DAG). It is always possible to find a topological order for a DAG and this can be done in linear time.
Topological sorting of a DAG can be found with DFS. During the depth-first traversal of the graph, just when a vertex finishes expanding (i.e., all its outlinks have been visited), add it to a stack. The order of vertices in the stack represents the topological order of the DAG.
Pseudocode for topological sorting :
Let L be an empty list | |
Let all vertices be initially unmarked | |
while there are unmarked vertices: | |
select an unmarked vertex u | |
dfs(u) | |
def dfs(vertex u): | |
mark u | |
foreach edge u -> v | |
if v is unmarked: | |
dfs(v) | |
add u to head of L | |
L represents the topological order of the DAG |
Thus, the time complexity of finding topological sorting is same as that of DFS i.e., O(V + E).
Take a look at C++ implementation.
Try your hand at problems TOPOSORT and RPLA, which use this idea.
Reference: Algorithms 4th Edition by Robert Sedgewick and Kevin Wayne
Hello sir,I somewhat used the same idea and tried to implement the code.Can you see this ones http://ideone.com/Y1jZyI I tried my hands on TOPOSORT on spoj
Hello sir,Have you done toposort on spoj using this implementation only ?I mean in that question it is required to print lexiographically smallest toposort.Have you done something with your code to get Ac in that question or just used this code only.As far as I know there can be many toposort for a DAG.So my question is that how to get Lexiographically smallest ?
This problem can be solved with Kahn’s algorithm: https://en.wikipedia.org/wiki/Topological_sorting#Algorithms
Thanks a lot 🙂