akashtadwai

BFS

Dec 5th, 2019
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.90 KB | None | 0 0
  1. // C++ program to print connected components in
  2. // an undirected graph
  3. #include<iostream>
  4. #include <list>
  5. using namespace std;
  6. #define ver 100005
  7. // Graph class represents a undirected graph
  8. // using adjacency list representation
  9. class Graph
  10. {
  11.     int V; // No. of vertices
  12.  
  13.     // Pointer to an array containing adjacency lists
  14.     list<int> *adj;
  15.  
  16.     // A function used by DFS  
  17. public:
  18.     Graph(int V); // Constructor
  19.   void BFS(int v, bool visited[]);
  20.     void addEdge(int v, int w);
  21.     void connectedComponents();
  22. };
  23.  
  24. // Method to print connected components in an
  25. // undirected graph
  26. void Graph::connectedComponents()
  27. {
  28.     // Mark all the vertices as not visited
  29.     bool *visited = new bool[V];
  30.     int cnt=0;
  31.     for(int v = 0; v < V; v++)
  32.         visited[v] = false;
  33.  
  34.     for (int v=0; v<V; v++)
  35.     {
  36.         if (visited[v] == false and adj[v].size()!=0)
  37.         {
  38.             // print all reachable vertices
  39.             // from v
  40.             BFS(v, visited);
  41.             cnt++;
  42.             cout << "\n";
  43.         }
  44.     }
  45.   cout<<cnt<<endl;
  46. }
  47. void Graph::BFS(int v, bool visited[])
  48. {
  49.   list<int> queue;
  50.   visited[v] = true;
  51.   queue.push_back(v);
  52.   list<int>::iterator i;
  53.   while (!queue.empty()) {
  54.     v = queue.front();
  55.     cout<<v<<" ";
  56.     queue.pop_front();
  57.     for (i = adj[v].begin(); i != adj[v].end(); ++i) {
  58.       if (!visited[*i]) {
  59.         visited[*i] = true;
  60.         queue.push_back(*i);
  61.       }
  62.     }
  63.   }
  64. }
  65.  
  66.  
  67. Graph::Graph(int V)
  68. {
  69.     this->V = V;
  70.     adj = new list<int>[V];
  71. }
  72.  
  73. // method to add an undirected edge
  74. void Graph::addEdge(int v, int w)
  75. {
  76.     adj[v].push_back(w);
  77.     adj[w].push_back(v);
  78. }
  79.  
  80. // Drive program to test above
  81. int main()
  82. {
  83.     // Create a graph given in the above diagram
  84.     Graph g(ver); // 5 vertices numbered from 0 to 4
  85.     g.addEdge(1, 0);
  86.     g.addEdge(2, 3);
  87.     g.addEdge(3, 4);
  88.  
  89.     cout << "Following are connected components \n";
  90.     g.connectedComponents();
  91.  
  92.     return 0;
  93. }
Add Comment
Please, Sign In to add comment