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