Introduction
Topological sort is focused on ordering of vertices in a directed
acyclic graph [DAG] in which each node comes before all nodes
to which it has outgoing edges.
Every DAG may have one or more topological orderings.
Topological sort is not possible if the graph has a cycle,
since for two vertices v and w on the cycle, v precedes w and
w precedes v.
This algorithm falls under Divide & Conquer Technique which is
divides the problem, finds the solution to smaller problem and
then merges these to get the solution to the original problem.
Let's look at the working of this algorithm.
Note:
-
We will be using 2D arrays(adjacency matrix) for implementing
graph.
- We shall implement a directed graph.
-
Make a point that the order of traversing actually can be
anything like ascending or descending or random, but will
stick to traverse each node in ascending order.
-
The output will differ because it depends on what vertex you
start with and in what order you traverse them.
Working Procedure
Do refer the code available the end of this section to
understand the following theory.
-
Inserting new vertices and edges is same as previously done in
Graph Traversal Techniques
except that here, it is a directed graph.
-
Let V be the number of vertices and E be the number of edges
in the graph.
-
Whenever a new edge is added from u->v, increment the indegree
of v only because it's a directed graph.
-
Topological Sort:
-
Initially push the vertices on to a stack whose indegree
is 0.
-
Loop from i=0 to V
-
Loop until the stack is not empty i.e top != -1.
-
Pop the top of stack and add it to the topological
order array.
-
Now decrement the indegree of the adjacent vertices of
this popped vertex and if indegree of the adjacent
vertex becomes zero then push it to the stack.
-
If the length of the topological order array is not equal
to V then the graph has a cycle.
-
Else we have the required topological sort in the
topological order array.
Time Complexity: O(V+E)