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. int x = STK.top();
  19. while(!STK.empty())
  20. {
  21. for(int j = 0; j < graph[x].size(); j++)
  22. {
  23. x = STK.top();
  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. }
  32. }
  33. STK.pop();
  34. }
  35. }
  36.  
  37.  
  38. void DFS_RC(int start)
  39. {
  40. visit[start] = 1;
  41. cout<<start<<" ";
  42.  
  43. for(int j = 0; j < graph[start].size();j++)
  44. {
  45. int node = graph[start][j];
  46. if(visit[node] == 0)
  47. {
  48. visit[node] = 1;
  49. DFS_RC(node);
  50. }
  51. }
  52. }
  53.  
  54.  
  55.  
  56. int main()
  57. {
  58. cin>>n>>e;
  59. int u, v;
  60. for(int i = 1; i <= e; i++)
  61. {
  62. cin>>u>>v;
  63. graph[u].push_back(v);
  64. graph[v].push_back(u);
  65. }
  66. DFS(1);
  67. //DFS_RC(1);
  68.  
  69.  
  70. }
  71.  
Success #stdin #stdout 0.01s 5316KB
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 0 9 5 6 7 8