fork download
  1. //
  2. // main.cpp
  3. // BFS Graph
  4. //
  5. // Created by Himanshu on 26/08/21.
  6. //
  7. #include <iostream>
  8. #include <queue>
  9. using namespace std;
  10.  
  11. //s= source
  12. //n = number of nodes in graph
  13. void BFS (int s, int n, vector<int> graph[]) {
  14. if (s == 0) {
  15. return;
  16. }
  17. int vis[n+1];
  18. queue<int> qu;
  19.  
  20. for (int i=1; i<=n; i++) {
  21. vis[i] = 0;
  22. }
  23. qu.push(s);
  24. vis[s] = 1;
  25. cout<<"BFS:"<<endl;
  26. cout<<s<<endl;
  27. while (!qu.empty()) {
  28. int node = qu.front();
  29. qu.pop();
  30. for (int i=0; i<graph[node].size(); i++) {
  31. int j = graph[node][i];
  32. if (vis[j] == 0) {
  33. vis[j] = 1;
  34. qu.push(j);
  35. cout<<j<<" ";
  36. }
  37. }
  38. cout<<endl;
  39. }
  40. cout<<endl;
  41. }
  42.  
  43.  
  44. int main() {
  45. int s = 1, n = 5;
  46. vector<int> graph[n+1];
  47. graph[1].push_back(2);
  48. graph[1].push_back(3);
  49. graph[2].push_back(1);
  50. graph[2].push_back(4);
  51. graph[3].push_back(1);
  52. graph[3].push_back(5);
  53. graph[4].push_back(2);
  54. graph[4].push_back(5);
  55. graph[5].push_back(3);
  56. graph[5].push_back(4);
  57.  
  58. cout<<"Graph:"<<endl;
  59. for (int i=1; i<=n; i++) {
  60. cout<<i<<": ";
  61. for (int j=0; j<graph[i].size(); j++) {
  62. cout<<graph[i][j]<<" ";
  63. }
  64. cout<<endl;
  65. }
  66. cout<<endl;
  67. BFS(s, n, graph);
  68. return 0;
  69. }
  70.  
Success #stdin #stdout 0s 5572KB
stdin
Standard input is empty
stdout
Graph:
1: 2 3 
2: 1 4 
3: 1 5 
4: 2 5 
5: 3 4 

BFS:
1
2 3 
4 
5