ASSIGNMENT-10
NILESH
KUMAR
06116403222
Btech CSE
USICT
Question-1 WAP to implement Topological sort.
CODE:
#include <iostream>
#include <vector>
#include <stack>
#include <unordered_set>
using namespace std;
class Graph {
int V; // Number of vertices
// Adjacency list
vector<vector<int>> adj;
// Helper function for DFS
void DFSUtil(int v, vector<bool> &visited, stack<int> &Stack) {
visited[v] = true;
// Recur for all vertices adjacent to this vertex
for (int u : adj[v]) {
if (!visited[u])
DFSUtil(u, visited, Stack);
// Push current vertex to stack which stores topological sort
[Link](v);
public:
Graph(int V) : V(V) {
[Link](V);
// Function to add an edge to the graph
void addEdge(int u, int v) {
adj[u].push_back(v);
}
// Function to perform topological sorting
void topologicalSort() {
stack<int> Stack;
vector<bool> visited(V, false);
// Call the recursive helper function to store topological
// sort starting from all vertices one by one
for (int i = 0; i < V; ++i) {
if (!visited[i])
DFSUtil(i, visited, Stack);
// Print contents of stack
while (![Link]()) {
cout << [Link]() << " ";
[Link]();
};
int main() {
// Create a graph given in the example
Graph g(6);
[Link](5, 2);
[Link](5, 0);
[Link](4, 0);
[Link](4, 1);
[Link](2, 3);
[Link](3, 1);
cout << "Topological Sort: ";
[Link]();
return 0;
OUTPUT:
Question-2 WAP to find SCC in graph.
CODE:
#include<iostream>
#include<list>
#include<stack>
#include<vector>
using namespace std;
class Graph {
int V;
list<int> *adj;
void fillOrder(int v, bool visited[], stack<int> &Stack);
void DFSUtil(int v, bool visited[]);
public:
Graph(int V);
void addEdge(int v, int w);
Graph getTranspose();
void printSCCs();
};
Graph::Graph(int V) {
this->V = V;
adj = new list<int>[V];
}
void Graph::DFSUtil(int v, bool visited[]) {
visited[v] = true;
cout << v << " ";
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); ++i)
if (!visited[*i])
DFSUtil(*i, visited);
}
Graph Graph::getTranspose() {
Graph g(V);
for (int v = 0; v < V; v++) {
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i) {
[Link][*i].push_back(v);
}
return g;
void Graph::addEdge(int v, int w) {
adj[v].push_back(w);
}
void Graph::fillOrder(int v, bool visited[], stack<int> &Stack) {
visited[v] = true;
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i)
if(!visited[*i])
fillOrder(*i, visited, Stack);
[Link](v);
}
void Graph::printSCCs() {
stack<int> Stack;
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
for(int i = 0; i < V; i++)
if(visited[i] == false)
fillOrder(i, visited, Stack);
Graph gr = getTranspose();
for(int i = 0; i < V; i++)
visited[i] = false;
while ([Link]() == false) {
int v = [Link]();
[Link]();
if (visited[v] == false) {
[Link](v, visited);
cout << endl;
}
}
}
int main() {
Graph g(5);
[Link](1, 0);
[Link](0, 2);
[Link](2, 1);
[Link](0, 3);
[Link](3, 4);
cout << "Strongly Connected Components are:\n";
[Link]();
return 0;
}
OUTPUT: