# C++ Program to Apply DFS to Perform the Topological Sorting of a Directed Acyclic Graph

C++Server Side ProgrammingProgramming

Topological sorting of DAG (Directed Acyclic Graph) is a linear ordering of vertices such that for every directed edge uv, where vertex u comes before v in the ordering. If the graph is not a DAG, Topological Sorting for a graph is not possible.

## Functions and pseudocodes

Begin
function topologicalSort():
a) Mark the current node as visited.
b) Recur for all the vertices adjacent to this vertex.
c) Push current vertex to stack which stores result.
End
Begin
function topoSort() which uses recursive topological sort() function:
a) Mark all the vertices which are not visited.
b) Call the function topologicalSort().
c) Print the content.
End

## Example

#include<iostream>
#include <list>
#include <stack>
using namespace std;
class G {
int n;
//declaration of functions
void topologicalSort(int v, bool visited[], stack<int> &Stack);
public:
G(int n); //constructor
void topoSort();
};
G::G(int n) {
this->n = n;
}
void G::addEd(int v, int w) // add the edges to the graph. {
}
void G::topologicalSort(int v, bool visited[], stack<int> &Stack) {
visited[v] = true; //mark current node as visited
list<int>::iterator i;
//Recur for all the vertices adjacent to this vertex.
if (!visited[*i])
topologicalSort(*i, visited, Stack);
Stack.push(v);
}
void G::topoSort() {
stack<int> Stack;
bool *visited = new bool[n];
//Mark all the vertices which are not visited.
for (int i = 0; i < n; i++)
visited[i] = false;
for (int i = 0; i < n; i++)
if (visited[i] == false)
//Call the function topologicalSort().
topologicalSort(i, visited, Stack);
while (Stack.empty() == false) {
cout << Stack.top() << " "; //print the element
Stack.pop();
}
}
int main() {
G g(6);
}
Topological Sort of the given graph
5 4 1 3 2 0