fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int>graph[1001];
  4. int visit[1001];
  5. int n, e;
  6.  
  7. void DFS_Stk(int start)
  8. {
  9. visit[start] = 1; //Initial Step
  10. cout<<start<<" ";
  11. stack<int>S;
  12. S.push(start);
  13.  
  14. while(!S.empty())
  15. {
  16. int x = S.top();
  17. for(int j = 0; j < graph[x].size(); j++)
  18. {
  19.  
  20. int node = graph[x][j];
  21. if(visit[node] == 0)
  22. {
  23. visit[node] = 1;
  24. cout<<node<<" ";
  25. S.push(node);
  26. j = 0;
  27. x = S.top();
  28. }
  29. }
  30. S.pop();
  31. }
  32.  
  33.  
  34.  
  35.  
  36.  
  37. }
  38.  
  39. void DFS_Rec(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_Rec(node);
  51. }
  52. }
  53. }
  54.  
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64. int main()
  65. {
  66. cin>>n>>e;
  67. int u, v;
  68. for(int i = 1; i <= e; i++)
  69. {
  70. cin>>u>>v;
  71. graph[u].push_back(v);
  72. graph[v].push_back(u);
  73. }
  74. //DFS_Stk(1);
  75. DFS_Rec(1);
  76. }
  77.  
Success #stdin #stdout 0.01s 5316KB
stdin
10 13
1 2
1 4
2 3
3 4
3 10
3 9
2 5
5 6
5 7
5 8
2 7
2 8
7 8
stdout
1 2 3 4 10 9 5 6 7 8