fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. vector<int> bfs(int start, vector<int> adj[], int n) {
  8. int vis[n + 1] = {0};
  9. vis[start] = 1;
  10. vector<int> bfsGraph;
  11. queue<int> q;
  12.  
  13. q.push(start);
  14. bfsGraph.push_back(start);
  15.  
  16. while (!q.empty()) {
  17. int node = q.front();
  18. q.pop();
  19. for (int it : adj[node]) {
  20. if (!vis[it]) {
  21. q.push(it);
  22. vis[it] = 1;
  23. bfsGraph.push_back(it);
  24. }
  25. }
  26. }
  27.  
  28. return bfsGraph;
  29. }
  30.  
  31. int main() {
  32. int n, m;
  33. cout << "Enter the number of nodes and edges: ";
  34. cin >> n >> m;
  35.  
  36. vector<int> adj[n + 1];
  37.  
  38. cout << "Enter the edges : " << endl;
  39. for (int i = 0; i < m; i++) {
  40. int u, v;
  41. cin >> u >> v;
  42. adj[u].push_back(v);
  43. adj[v].push_back(u);
  44. }
  45.  
  46. int start;
  47. cout << "Enter the starting node: ";
  48. cin >> start;
  49.  
  50.  
  51. vector<int> bfsResult = bfs(start, adj, n);
  52.  
  53. cout << "BFS traversal order: ";
  54. for (int i = 0; i < bfsResult.size(); i++) {
  55. cout << bfsResult[i] << " ";
  56. }
  57. cout << endl;
  58.  
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0.01s 5268KB
stdin
Standard input is empty
stdout
Enter the number of nodes and edges: Enter the edges : 
Enter the starting node: BFS traversal order: 21936