fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int graph[1000][1000];
  4. int visit[1000];
  5. int n, e;
  6. //jekunu array globally declare korle tar shob value 0 hoye jay that's why we don't need memset
  7.  
  8. void BFS(int source)
  9. {
  10. visit[source]=1; //start of the initial step of BFS
  11. cout<<source<<" ";
  12. queue<int>q;
  13. q.push(source); //end of initial step of BFS
  14.  
  15. while(!q.empty()) //the initial step will keep on repeating until the values are popped, in other words when the queue is empty
  16. {
  17. int x = q.front(); // this is so that the values don't get lost after being popped
  18. q.pop();
  19. for(int j=1; j<=n; j++) //this indicates column of a matrix
  20. {
  21. if(graph[x][j]!=0 && visit[j]==0) //we don't give 1 instead of !0 as their are graphs which has weight
  22. {
  23. visit[j]=1;
  24. cout<<j<<" ";
  25. q.push(j);
  26. }
  27.  
  28. }
  29. }
  30.  
  31. }
  32.  
  33. int main()
  34. {
  35.  
  36. cout<<"Enter node and edge:";
  37. cin>>n>>e;
  38.  
  39. int u,v;
  40. for(int i=1; i<=e; i++)
  41. {
  42. cin>>u>>v;
  43. graph[u][v]=1;
  44. graph[v][u]=1;
  45. }
  46.  
  47. BFS(1);
  48.  
  49. return 0;
  50. }
  51.  
  52. /*
  53. 10 13
  54. 1 2
  55. 1 4
  56. 4 3
  57. 2 3
  58. 3 10
  59. 3 9
  60. 2 8
  61. 2 7
  62. 2 5
  63. 5 6
  64. 8 7
  65. 5 7
  66. 5 8
  67.  
  68. */
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
Success #stdin #stdout 0.01s 5296KB
stdin
Standard input is empty
stdout
Enter node and edge:1