fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int graph[1001][1001];
  4. int visit[1001]; //globally declaring an array means array value is 1;
  5. int n,e;
  6. void DFS(int start)
  7. {
  8. //initial step
  9. visit[start]=1;
  10. cout<<start<<" ";
  11. stack<int>stk;
  12. stk.push(start);
  13.  
  14. //repeating step
  15. while(!stk.empty())
  16. {
  17. for(int j=1;j<=n;j++)
  18. {
  19. int x= stk.top();
  20. if(visit[j]==0 && graph[x][j]!=0)
  21. {
  22. visit[j]=1;
  23. cout<<j<<" ";
  24. stk.push(j);
  25. j=1;
  26. }
  27. }
  28. stk.pop();
  29. }
  30. }
  31.  
  32. int main()
  33. {
  34. cin>>n>>e;
  35. int u,v;
  36. for(int i=1;i<=e;i++)
  37. {
  38. cin>>u>>v;
  39. graph[u][v]=1;
  40. graph[v][u]=1;
  41. }
  42. DFS(1);
  43.  
  44.  
  45.  
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 5288KB
stdin
Standard input is empty
stdout
1