fork download
  1.  
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. vector<int>graph[1001];
  5. int visit[1001];
  6. int n, e;
  7.  
  8. void DFS(int start)
  9. {
  10. //Using Stack
  11. //Initial Steps
  12. visit[start] = 1;
  13. stack<int>STK;
  14. STK.push(start);
  15. cout<<start<<" ";
  16.  
  17. //Repeating step
  18.  
  19. while(!STK.empty())
  20. {
  21. int x = STK.top();
  22. for(int j = 0; j < graph[x].size(); j++)
  23. {
  24. int nd = graph[x][j];
  25. if(visit[nd] == 0)
  26. {
  27. visit[nd] = 1;
  28. STK.push(nd);
  29. cout<<nd<<" ";
  30. j = 0;
  31. x = STK.top();
  32. }
  33. }
  34. STK.pop();
  35. }
  36. }
  37.  
  38.  
  39. void DFS_RC(int start)
  40. {
  41. visit[start] = 1;
  42. cout<<start<<" ";
  43.  
  44. for(int j = 0; j < graph[start].size();j++)
  45. {
  46. int node = graph[start][j];
  47. if(visit[node] == 0)
  48. {
  49. visit[node] = 1;
  50. DFS_RC(node);
  51. }
  52. }
  53. }
  54.  
  55.  
  56.  
  57. int main()
  58. {
  59. cin>>n>>e;
  60. int u, v;
  61. for(int i = 1; i <= e; i++)
  62. {
  63. cin>>u>>v;
  64. graph[u].push_back(v);
  65. graph[v].push_back(u);
  66. }
  67. DFS(1);
  68. //DFS_RC(1);
  69.  
  70.  
  71. }
  72.  
Success #stdin #stdout 0.01s 5320KB
stdin
10 13
1 2
2 3
3 4
3 10
3 9
2 5
2 7
2 8
5 6
5 7
5 8
7 8
4 1
stdout
1 2 3 4 10 9 5 6 7 8