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