fork(39) download
  1. #include <iostream>
  2. #include <stack>
  3. #include <algorithm>
  4. using namespace std;
  5.  
  6. int main() {
  7. stack<pair<bool,int> > dfs;
  8. stack<int> postOrder;
  9. vector<int> newVec;
  10. vector<int>::iterator it;
  11. vector<vector<int> > graph {
  12. {1, 2}
  13. , {2, 3}
  14. , {3, 4, 7}
  15. , {4}
  16. , {5}
  17. , {6, 7}
  18. , {}
  19. , {6}
  20. };
  21. vector<bool> visited(graph.size());
  22. for(int i=0;i<graph.size();i++){
  23. if(visited[i]==false){
  24. dfs.push(make_pair(false,i));
  25. }
  26. while(!dfs.empty()){
  27. pair<bool,int> node=dfs.top();
  28. dfs.pop();
  29. if (node.first) {
  30. postOrder.push(node.second);
  31. cout << node.second << endl;
  32. continue;
  33. }
  34. visited[node.second]=true;
  35. dfs.push(make_pair(true, node.second));
  36. newVec=graph[node.second]; //vector of neighboors
  37. for(it=newVec.begin();it!=newVec.end();it++){
  38. int son=*it;
  39. if(visited[son]==false){
  40. dfs.push(make_pair(false, son));
  41. }
  42. }
  43. }
  44. }
  45. return 0;
  46. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
6
7
5
4
3
2
1
0