fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. vector<int>graph[1001];
  4. int visit[1001];
  5. int node, edge;
  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. cout<<x<<" ";
  20. Q.pop();
  21.  
  22. for(int j = 0; j < graph[x].size(); j++)
  23. {
  24. int nd = graph[x][j];
  25. if(visit[nd] == 0)
  26. {
  27. visit[nd] = 1;
  28. //cout<<nd<<" ";
  29. Q.push(nd);
  30. }
  31. }
  32.  
  33. }
  34.  
  35.  
  36.  
  37. }
  38.  
  39. int main()
  40. {
  41. cin>>node>>edge;
  42. int u, v;
  43. for(int i = 1; i <= edge; i++)
  44. {
  45. cin>>u>>v;
  46. graph[u].push_back(v);
  47. graph[v].push_back(u);
  48. }
  49.  
  50. BFS(1);
  51.  
  52. }
  53.  
  54.  
Success #stdin #stdout 0.01s 5284KB
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