fork 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.  
  8. void DFS(int start)
  9. {
  10. //Initial Step
  11. visit[start] = 1;
  12. cout<<start<<" ";
  13. stack<int>stk;
  14. stk.push(start);
  15.  
  16. //Repeating Step
  17. while(!stk.empty())
  18. {
  19.  
  20. for(int j = 1; j <= n; j++)
  21. {
  22. int x = stk.top();
  23. if(visit[j] == 0 && graph[x][j] != 0)
  24. {
  25. visit[j] = 1;
  26. cout<<j<<" ";
  27. stk.push(j);
  28. j = 1;
  29. }
  30. }
  31. stk.pop();
  32. }
  33. }
  34.  
  35. int main()
  36. {
  37. cin>>n>>e;
  38. int u, v;
  39. for(int i = 1; i <= e; i++)
  40. {
  41. cin>>u>>v;
  42. graph[u][v] = 1;
  43. graph[v][u] = 1;
  44. }
  45. DFS(1);
  46. }
  47.  
Success #stdin #stdout 0s 5288KB
stdin
10 13                                                                            1 2                                                                              1 4                                                                              2 3                                                                              4 3                                                                              3 9                                                                              3 10                                                                             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