Skip to content

Commit 7d30c9f

Browse files
authored
Create main.cpp
1 parent 167fdcd commit 7d30c9f

File tree

1 file changed

+51
-0
lines changed
  • 23 - Graph Data Structure Problems/09 - Topological Sort using DFS

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// Function to perform DFS and topological sorting
5+
void topologicalSortUtil(int node, vector<vector<int> >& adj, vector<bool>& visited, stack<int>& Stack){
6+
// Mark the current node as visited
7+
visited[node] = true;
8+
9+
// Recur for all adjacent vertices
10+
for (auto neighbour : adj[node]) if (!visited[neighbour]) topologicalSortUtil(neighbour, adj, visited, Stack);
11+
12+
// Push current vertex to stack which stores the result
13+
Stack.push(node);
14+
}
15+
16+
// Function to perform Topological Sort
17+
void topologicalSort(vector<vector<int> >& adj, int V){
18+
stack<int> Stack; // Stack to store the result
19+
vector<bool> visited(V, false);
20+
21+
// Call the recursive helper function to store
22+
// Topological Sort starting from all vertices one by
23+
// one
24+
for (int i = 0; i < V; i++) if (!visited[i]) topologicalSortUtil(i, adj, visited, Stack);
25+
26+
// Print contents of stack
27+
while (!Stack.empty()) {
28+
cout << Stack.top() << " ";
29+
Stack.pop();
30+
}
31+
}
32+
33+
int main()
34+
{
35+
36+
// Number of nodes
37+
int V = 4;
38+
39+
// Edges
40+
vector<vector<int> > edges = {{0, 1}, {1, 2}, {3, 1}, {3, 2}};
41+
42+
// Graph represented as an adjacency list
43+
vector<vector<int> > adj(V);
44+
45+
for (auto i : edges) adj[i[0]].push_back(i[1]);
46+
47+
cout << "Topological sorting of the graph: ";
48+
topologicalSort(adj, V);
49+
50+
return 0;
51+
}

0 commit comments

Comments
 (0)