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