Skip to content

Commit 86bb00b

Browse files
authored
Merge pull request #129 from Sugyanee/add-graph-algorithm-cpp
Add Topological sorting algorithm cpp
2 parents cd0f6bf + c52e252 commit 86bb00b

1 file changed

Lines changed: 85 additions & 0 deletions

File tree

CPP/graph/topological_sorting.cpp

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/****************************************
2+
Problem: Topological Sorting of a Directed Acyclic Graph (DAG)
3+
4+
Description:
5+
Given a Directed Acyclic Graph (DAG) with V vertices and E edges,
6+
find any valid topological ordering of the graph. In a topological
7+
ordering, for every directed edge u -> v, node u will always appear
8+
before node v in the ordering.
9+
10+
This ordering is useful in scenarios such as task scheduling,
11+
course prerequisite resolution, and resolving symbol dependencies
12+
in compilers.
13+
14+
Time Complexity: O(V + E) - each vertex and edge is processed once
15+
Space Complexity: O(V + E) - adjacency list, in-degree array/stack/queue, and output list
16+
****************************************/
17+
18+
#include <bits/stdc++.h>
19+
using namespace std;
20+
21+
class Solution {
22+
private:
23+
// Helper function to perform DFS and push nodes into stack
24+
void dfs(int node, int vis[], stack<int> &st,
25+
vector<int> adj[]) {
26+
vis[node] = 1; // Mark node as visited
27+
28+
for (auto it : adj[node]) { // Visit all unvisited neighbors
29+
if (!vis[it]) dfs(it, vis, st, adj);
30+
}
31+
32+
// Once all neighbors are processed, push current node
33+
st.push(node);
34+
}
35+
public:
36+
//Function to return list containing vertices in Topological order.
37+
vector<int> topoSort(int V, vector<int> adj[])
38+
{
39+
int vis[V] = {0};
40+
stack<int> st;
41+
42+
// Run DFS from every unvisited node
43+
for (int i = 0; i < V; i++) {
44+
if (!vis[i]) {
45+
dfs(i, vis, st, adj);
46+
}
47+
}
48+
49+
// Extract nodes from stack to get topological order
50+
vector<int> ans;
51+
while (!st.empty()) {
52+
ans.push_back(st.top());
53+
st.pop();
54+
}
55+
return ans;
56+
}
57+
};
58+
59+
60+
int main() {
61+
62+
// Example graph:
63+
// V = 6
64+
// Edges: 2 -> 3, 3 -> 1, 4 -> 0, 4 -> 1, 5 -> 0, 5 -> 2
65+
vector<int> adj[6] = {{}, {}, {3}, {1}, {0, 1}, {0, 2}};
66+
int V = 6;
67+
Solution obj;
68+
vector<int> ans = obj.topoSort(V, adj);
69+
cout<<"Topological sorting: ";
70+
for (auto node : ans) {
71+
cout << node << " ";
72+
}
73+
cout << endl;
74+
75+
return 0;
76+
}
77+
78+
/****************************************
79+
Expected Output for the test case:
80+
81+
Topological Sorting: 5 4 2 3 1 0
82+
83+
(Note: For topological sort, multiple valid outputs are possible.
84+
For example, "4 5 2 3 1 0" is also valid.)
85+
****************************************/

0 commit comments

Comments
 (0)