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