Skip to content

Commit ebde72e

Browse files
committed
add topological sorting
1 parent ed36395 commit ebde72e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Graph/topological_sort.cpp

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
/*
5+
Time Complexity: O(V+E)+O(V), where V = no. of nodes and E = no. of edges. There can be at most V components. So, another O(V) time complexity.
6+
7+
Space Complexity: O(2N) + O(N) ~ O(2N): O(2N) for the visited array and the stack carried during DFS calls and O(N) for recursive stack space, where N = no. of nodes.
8+
9+
https://youtu.be/5lZ0iJMrUMk
10+
*/
11+
12+
class Solution{
13+
private:
14+
void dfs(int node, vector<int> &visited, stack<int> &st, vector<int> adj[])
15+
{
16+
visited[node] = 1;
17+
for(int neighbour: adj[node])
18+
{
19+
if(!visited[neighbour])
20+
dfs(neighbour, visited, st, adj);
21+
}
22+
23+
st.push(node);
24+
}
25+
26+
public:
27+
vector<int> topoSort(int V, vector<int> adj[])
28+
{
29+
vector<int> visited(V, 0);
30+
stack<int> st;
31+
for (int i = 0; i < V; i++)
32+
if(!visited[i])
33+
dfs(i, visited, st, adj);
34+
35+
vector<int> ans;
36+
while(!st.empty())
37+
{
38+
ans.push_back(st.top());
39+
st.pop();
40+
}
41+
42+
return ans;
43+
}
44+
};

0 commit comments

Comments
 (0)