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. visit[start] =1;
  10. cout << start << " ";
  11. queue<int>Q;
  12. Q.push(start);
  13.  
  14. while(!Q.empty())
  15. {
  16. int x = Q.front();
  17. Q.pop();
  18. for(int j = 0 ; j< graph[x].size();j++)
  19. {
  20. int node = graph[x][j];
  21. if(visit[node] == 0)
  22. {
  23.  
  24. visit[node] =1;
  25. cout << node << " ";
  26. Q.push(node);
  27. }
  28. }
  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].push_back(v);
  40. graph[v].push_back(u);
  41. }
  42.  
  43. BFS(1);
  44.  
  45.  
  46.  
  47. return 0;
  48. }
  49.  
Success #stdin #stdout 0s 5312KB
stdin
10 13
1 2
1 4
4 3
2 3
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