I know the common way to do a topological sort is using DFS with recursion. But how would you do it using stack
instead of recursion? I need to obtai
The Graph structure is as folows
N
: number of vertices
adj[]
: input graph
vector<int> topoSort(int V, vector<int> adj[]) {
stack<int> s;
vector<int> f(V,0);
stack<int> out;
int i,j,x;
for(i=0;i<V;i++){
if(f[i]==0){
s.push(i);
while(!s.empty()){
x = s.top();
s.pop();
if(f[x]==1){
out.push(x);
continue;
}
f[x] = 1;
s.push(x);
for(j=0;j<adj[x].size();j++){
if(f[adj[x][j]]==0){
s.push(adj[x][j]);
}
}
}
}
}
vector<int> output;
while(!out.empty()){
x=out.top();
out.pop();
//cout << x << " ";
output.push_back(x);
}
//cout << endl;
return output;
}