pankovamg

DFS norecursion

Nov 21st, 2021 (edited)
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5. int n, m;
  6. vector <vector<int>> g;
  7. vector <bool> used;
  8. vector <int> q;
  9.  
  10. int main() {
  11. cin >> n >> m;
  12. g.resize(n);
  13. used.resize(n, false);
  14. for (int i = 0; i < m; i++){
  15. int x, y;
  16. cin >> x >> y;
  17. x--; y--;
  18. g[x].push_back(y);
  19. g[y].push_back(x);
  20. }
  21. q.push_back(0);
  22. used[0] = true;
  23. while(!q.empty()){
  24. int v = q.back();
  25. bool fl = true;
  26. int j = 0;
  27. while (j < g[v].size()){
  28. if (!used[g[v][j]]){
  29. fl = false;
  30. break;
  31. }
  32. else j++;
  33. }
  34.  
  35. if (!fl){
  36. q.push_back(g[v][j]);
  37. cout << v+1 <<' '<<g[v][j]+1 <<'\n';
  38. used[g[v][j]] = true;
  39. }
  40. else q.pop_back();
  41. }
  42. return 0;
  43. }
  44.  
Add Comment
Please, Sign In to add comment