fork download
  1. #include <iostream>
  2. using namespace std;
  3. #include <bits/stdc++.h>
  4.  
  5. void DFS(int node,vector<int>b[],vector<int>&parent,vector<int>&used)
  6. {
  7. cout<<node<<" ";
  8. used[node]=1;
  9. for(auto x:b[node])
  10. {
  11. if(used[x]==0)
  12. {
  13. parent[x]=node;
  14. DFS(x,b,parent,used);
  15. }
  16. }
  17. }
  18.  
  19. int main() {
  20. // your code goes here
  21. int n,m;
  22. cin>>n>>m;
  23. int i;
  24. vector<int>b[n+5];
  25. for(i=1;i<=m;i++)
  26. {
  27. int x,y;
  28. cin>>x>>y;
  29. b[x].push_back(y);
  30. b[y].push_back(x);
  31. }
  32.  
  33. vector<int>used(n+5,0);
  34. vector<int>parent(n+5,0);
  35.  
  36. DFS(1,b,parent,used);
  37. return 0;
  38. }
Success #stdin #stdout 0s 5292KB
stdin
8 7
1 2
1 3
2 4
2 5
4 8
3 6
3 7
stdout
1 2 4 8 5 3 6 7