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