fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void bfs(vector<vector<int>> &adj, int s) {
  5. queue<int> q;
  6. vector<bool> visited(adj.size(), false);
  7. visited[s] = true;
  8. q.push(s);
  9. while(!q.empty()){
  10. int curr = q.front();
  11. q.pop();
  12. cout<<curr<<" ";
  13. for(int x : adj[curr]){
  14. if(!visited[x]) {
  15. visited[x] = true;
  16. q.push(x);
  17. }
  18. }
  19. }
  20. }
  21.  
  22. int main() {
  23. int n = 5;
  24. vector<vector<int>> adj(n);
  25. adj[0].push_back(1);
  26. adj[0].push_back(2);
  27. adj[1].push_back(0);
  28. adj[1].push_back(2);
  29. adj[2].push_back(3);
  30. adj[2].push_back(4);
  31. adj[3].push_back(4);
  32. adj[3].push_back(1);
  33. adj[4].push_back(3);
  34. adj[4].push_back(2);
  35. bfs(adj,0);
  36. return 0;
  37. }
Success #stdin #stdout 0.01s 5280KB
stdin
Standard input is empty
stdout
0 1 2 3 4