Guest User

Untitled

a guest
Jul 20th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. class Graph
  4. {
  5. int V;
  6. list<int> *adj;
  7. public:
  8. Graph(int V);
  9. void addEdge(int u, int v);
  10. void BFS(int s);
  11. };
  12.  
  13. Graph::Graph(int V)
  14. {
  15. this->V=V;
  16. adj = new list<int>[V];
  17. }
  18.  
  19. void Graph::addEdge(int u, int v)
  20. {
  21. adj[u].push_back(v);
  22. }
  23.  
  24. void Graph::BFS(int s)
  25. {
  26. bool *visited = new bool[V];
  27. for(int i=0; i<V; i++)
  28. visited[i] = false;
  29. list<int> queue;
  30. visited[s]=true;
  31. queue.push_back(s);
  32. while(!queue.empty())
  33. {
  34. s = queue.front();
  35. cout<<s<<" ";
  36. queue.pop_front();
  37. list<int> ::iterator i;
  38. for(i=adj[s].begin(); i!=adj[s].end(); i++)
  39. {
  40. if(!visited[*i])
  41. {
  42. visited[*i] = true;
  43. queue.push_back(*i);
  44. }
  45. }
  46. }
  47. }
  48.  
  49. int main()
  50. {
  51. // Create a graph given in the above diagram
  52. Graph g(4);
  53. g.addEdge(0, 1);
  54. g.addEdge(0, 2);
  55. g.addEdge(1, 2);
  56. g.addEdge(2, 0);
  57. g.addEdge(2, 3);
  58. g.addEdge(3, 3);
  59.  
  60.  
  61. cout << "Following is Breadth First Traversal "
  62. << "(starting from vertex 2) \n";
  63. g.BFS(2);
  64.  
  65. return 0;
  66. }
Add Comment
Please, Sign In to add comment