fork(1) download
  1. #include<iostream>
  2. #include<map>
  3. #include<list>
  4. #include<queue>
  5. using namespace std;
  6.  
  7. template<typename T>
  8. class graph{
  9. map<T,list<T> >l;
  10. public:
  11. void addEdge(int x, int y){
  12. l[x].push_back(y);
  13. l[y].push_back(x);
  14. }
  15.  
  16. void bfs(T src){
  17. queue<T>q;
  18. map<int, bool>visited;
  19.  
  20. q.push(src);
  21. visited[src] = true;
  22.  
  23. while(!q.empty()){
  24. T node = q.front();
  25. q.pop();
  26. cout<<node<<" ";
  27. for(int nbr: l[node]){
  28. if(!visited[nbr]){
  29. q.push(nbr);
  30. //mark tht nbr as visited
  31. visited[nbr] = true;
  32. }
  33. }
  34. }
  35. }
  36.  
  37. };
  38. int main()
  39. {
  40. graph<int>g;
  41. g.addEdge(0,1);
  42. g.addEdge(1,2);
  43. g.addEdge(2,3);
  44. g.addEdge(3,4);
  45. g.addEdge(4,5);
  46. g.bfs(0);
  47. return 0;}
  48.  
Success #stdin #stdout 0s 4320KB
stdin
Standard input is empty
stdout
0 1 2 3 4 5