fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int>bfs(vector<int>graph[],int start, int n){
  5. int vis[n+1] ={0};
  6. queue<int>q;
  7. vector<int>bfsGraph;
  8. vis[start]=1;
  9. bfsGraph.push_back(start);
  10. q.push(start);
  11. while(q.size()){
  12. int node = q. front();
  13. q.pop();
  14. for(int x:graph[node]){
  15. if(!vis[x]){
  16. vis[x]++;
  17. q.push(x);
  18. bfsGraph.push_back(x);
  19. }
  20. }
  21. }
  22. return bfsGraph;
  23. }
  24.  
  25. int main(){
  26. int n, m; cin >> n >> m;
  27. vector<int>graph[n+1];
  28. for(int i = 0; i < m; i++){
  29. int x, y; cin >> x >> y;
  30. graph[x].push_back(y);
  31. graph[y].push_back(x);
  32. }
  33. vector<int>ans = bfs(graph,1,n);
  34. for(int i:ans){
  35. cout << i << ' ';
  36. }
  37. cout << '\n';
  38.  
  39. return 0;
  40. }
  41.  
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
1