Topological Sorting
Topological Sorting
Input: Graph :
Example
Output: 5 4 2 3 1 0
Explanation: The first vertex in topological sorting is always a vertex
with an in-degree of 0 (a vertex with no incoming edges). A
topological sorting of the following graph is “5 4 2 3 1 0”. There can be
more than one topological sorting for a graph. Another topological
sorting of the following graph is “4 5 2 3 1 0”.
This is due to the fact that undirected edge between two vertices u
and v means, there is an edge from u to v as well as from v to u.
Because of this both the nodes u and v depend upon each other and
none of them can appear before the other in the topological ordering
without creating a contradiction.
From the above image you would have already realized that there exist
multiple ways to get dressed, the below image shows some of those
ways.
Can you list all the possible topological ordering of getting dressed for
above dependency graph?
Algorithm for Topological Sorting using DFS:
Here’s a step-by-step algorithm for topological sorting using Depth First
Search (DFS):
Create a graph with n vertices and m-directed edges.
Initialize a stack and a visited array of size n.
For each unvisited vertex in the graph, do the following:
Call the DFS function with the vertex as the parameter.
In the DFS function, mark the vertex as visited and recursively
call the DFS function for all unvisited neighbors of the vertex.
Once all the neighbors have been visited, push the vertex onto
the stack.
After all, vertices have been visited, pop elements from the stack and
append them to the output list until the stack is empty.
The resulting list is the topologically sorted order of the graph.
Step 1:
We start DFS from node 0 because it has zero incoming Nodes
We push node 0 in the stack and move to next node having
minimum number of adjacent nodes i.e. node 1.
Step 2:
In this step , because there is no adjacent of this node so push the
node 1 in the stack and move to next node.
Step 3:
In this step , We choose node 2 because it has minimum number of
adjacent nodes after 0 and 1 .
We call DFS for node 2 and push all the nodes which comes in
traversal from node 2 in reverse order.
So push 3 then push 2 .
Step 4:
We now call DFS for node 4
Because 0 and 1 already present in the stack so we just push node
4 in the stack and return.
Step 5:
In this step because all the adjacent nodes of 5 is already in the
stack we push node 5 in the stack and return.
int main()
{
// Number of nodes
int V = 4;
// Edges
vector<vector<int> > edges
= { { 0, 1 }, { 1, 2 }, { 3, 1 }, { 3, 2 } };
return 0;
}
Output
Topological sorting of the graph: 3 0 1 2
Time Complexity: O(V+E). The above algorithm is simply DFS with an extra
stack. So time complexity is the same as DFS
Auxiliary space: O(V). The extra space is needed for the stack