...

/

Solution: Topological Sorting of a Graph

Solution: Topological Sorting of a Graph

This review provides a detailed analysis of the solution to perform topological sorting of a graph.

Solution #1: Using Graph Traversal

We can modify graph traversal algorithms to find Topological Sorting of a graph.

Press + to interact
main.cpp
Graph.cpp
Graph.h
#include "Graph.h"
void Graph::utilityFunction(int v, vector<bool>& visited, stack<int> &myStack) {
visited[v] = true;
list<int>::iterator i;
for (i = adjacencyList[v].begin(); i != adjacencyList[v].end(); ++i)
if (!visited[*i])
utilityFunction(*i, visited, myStack);
myStack.push(v);
}
void Graph::topologicalSort() {
vector<bool> visited(this -> vertices, false);
stack<int> myStack;
for (int i = 0; i < this -> vertices; i++)
if (visited[i] == false)
utilityFunction(i, visited, myStack);
while (myStack.empty() == false) {
cout << myStack.top() << " ";
myStack.pop();
}
}
int main() {
Graph g(6);
g.addEdge(5, 0);
g.addEdge(5, 2);
g.addEdge(4, 2);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Graph1 Topological Sort: ";
g.topologicalSort();
cout << endl << endl;
Graph g1(5);
g1.addEdge(0 ,1);
g1.addEdge(1 ,2);
g1.addEdge(2 ,3);
g1.addEdge(2 ,4);
g1.addEdge(3, 4);
g1.addEdge(0, 3);
cout << "Graph2 Topological Sort: ";
g1.topologicalSort();
return 0;
}

While traversing a graph, we start from a vertex. First, print it and then recursively call the utility function for its adjacent vertices.

In topological sorting, we use a temporary stack. We do not print the vertex immediately; before that, we recursively call topological sorting for all its adjacent vertices, then push it to a stack. Finally, print contents of the stack.

Note: A vertex is pushed to stack only when all of its adjacent vertices are already in the stack. ...

Pseudocode

function utilityFunction(v)
    mark v visited
    for
Access this course and 1400+ top-rated courses and projects.