fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int>graph[1001];
  4. int visit[1001];
  5. int n, e;
  6.  
  7. void BFS(int start)
  8. {
  9. //Initial Step
  10. visit[start] = 1;
  11. cout<<start<<" ";
  12. queue<int>q;
  13. q.push(start);
  14.  
  15. //Repeating Step
  16. while(!q.empty())
  17. {
  18. int x = q.front();
  19. q.pop();
  20. for(int j = 0; j < graph[x].size(); j++)
  21. {
  22. int node = graph[x][j];
  23. if(visit[node] == 0)
  24. {
  25. visit[node] = 1;
  26. cout<<node<<" ";
  27. q.push(node);
  28. }
  29. }
  30. }
  31.  
  32.  
  33.  
  34. }
  35.  
  36. int main()
  37. {
  38. cin>>n>>e;
  39. int u, v;
  40. for(int i = 1; i <= e; i++)
  41. {
  42. cin>>u>>v;
  43. graph[u].push_back(v);
  44. graph[v].push_back(u);
  45. }
  46. BFS(1);
  47. }
  48.  
Success #stdin #stdout 0.01s 5288KB
stdin
10 13                                                                            1 2                                                                              1 4                                                                              2 3                                                                              3 4                                                                              3 9                                                                              3 10                                                                             2 5                                                                              2 7                                                                              2 8                                                                              5 6                                                                              5 7                                                                              5 8                                                                              7 8
stdout
1 2 4 3 5 7 8 9 10 6