In a depth-first topological ordering, we start with finding a vertex that has n
ID: 3578474 • Letter: I
Question
In a depth-first topological ordering, we start with finding a vertex that has
no successors (such a vertex exists because the graph has no cycles), and place
it last in the topological order. After we have placed all the successors of a
vertex in topological order, we place the vertex in the topological order
before any of its successors. Clearly, in the depth-first topological ordering,
first we find the vertex to be placed in topologicalOrder[n-1], then
topologicalOrder[n-2], and so on.
Write the definitions of the C++ functions to implement the depth-first topological
ordering. Add these functions to the class topologicalOrderType,
which is derived from the class graphType. Also, write a program to test your
depth-first topological ordering.
Explanation / Answer
#include<iostream> // header files
#include <list>
#include <stack>
using namespace std;
class Graph{ // Class to represent a graph
int V; // No. of vertices'
list<int> *adj; // Pointer to an array containing adjacency listsList
void topologicalSortUtil(int v, bool visited[], stack<int> &Stack); // A function used by topologicalSort
public:
Graph(int V); // Constructor
void addEdge(int v, int w); // function to add an edge to graph
void topologicalSort(); // prints a Topological Sort of the complete graph
};
Graph::Graph(int V){
this->V = V;
adj = new list<int> [V];
}
void Graph::addEdge(int v, int w){
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::topologicalSortUtil(int v, bool visited[], stack<int> &Stack) // A recursive function used by topologicalSort
{ // Mark the current node as visited.
visited[v] = true; // Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
topologicalSortUtil(*i, visited, Stack);
Stack.push(v); // Push current vertex to stack which stores result
}
void Graph::topologicalSort(){// The function to do Topological Sort. It uses recursive topologicalSortUtil()
stack<int> Stack;
bool *visited = new bool[V]; // Mark all the vertices as not visited
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i = 0; i < V; i++) // Call the recursive helper function to store Topological Sort starting from all vertices one by one
if (visited[i] == false)
topologicalSortUtil(i, visited, Stack);
while (Stack.empty() == false) { // Print contents of stack
cout << Stack.top() << " ";
Stack.pop();
}
}
int main(){ // Driver program to test above functions
Graph g(6); // Create a graph given in the above diagram
g.addEdge(5, 2); // adding edges to graph
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Following is a Topological Sort of the given graph ";
g.topologicalSort();
return 0;
}// end of main
OUTPUT:
Following is a Topological Sort of the given graph
5 4 2 3 1 0