Advertisement
fayeakuzzamantonmoy

BFS

Jul 8th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1. #include <iostream>
  2. #include <list>
  3.  
  4. using namespace std;
  5.  
  6. class Graph
  7. {
  8.     int V;
  9.     list<int> *adj;
  10.  
  11. public:
  12.     Graph(int V);
  13.  
  14.     void addEdge(int v, int w);
  15.  
  16.     void BFS(int s,int d);
  17. };
  18.  
  19. Graph::Graph(int V)
  20. {
  21.     this->V = V;
  22.     adj = new list<int>[V];
  23. }
  24.  
  25. void Graph::addEdge(int v, int w)
  26. {
  27.     adj[v].push_back(w);
  28. }
  29.  
  30. void Graph::BFS(int s,int d)
  31. {
  32.     bool *visited = new bool[V];
  33.     for (int i = 0; i < V; i++)
  34.         visited[i] = false;
  35.  
  36.     list<int> queue;
  37.  
  38.     visited[s] = true;
  39.     queue.push_back(s);
  40.  
  41.     list<int>::iterator i;
  42.  
  43.     while (!queue.empty())
  44.     {
  45.         s = queue.front();
  46.         cout << s << " ";
  47.         if(s==d) break;
  48.         queue.pop_front();
  49.  
  50.         for (i = adj[s].begin(); i != adj[s].end(); ++i)
  51.         {
  52.             if (!visited[*i])
  53.             {
  54.                 visited[*i] = true;
  55.                 queue.push_back(*i);
  56.             }
  57.         }
  58.     }
  59. }
  60.  
  61. int main()
  62. {
  63.     Graph g(6);
  64.     g.addEdge(0, 1);
  65.     g.addEdge(0, 2);
  66.     g.addEdge(1, 3);
  67.     g.addEdge(1, 5);
  68.     g.addEdge(2, 0);
  69.     g.addEdge(2, 3);
  70.     g.addEdge(3, 2);
  71.     g.addEdge(3, 4);
  72.     g.addEdge(4, 3);
  73.     g.addEdge(4, 5);
  74.     g.addEdge(5, 1);
  75.     g.addEdge(5, 4);
  76.  
  77.     cout << "Please provide the Source:  \n";
  78.     int a;
  79.     cin>>a;
  80.     cout << "Please provide the Destination:  \n";
  81.     int d;
  82.     cin>>d;
  83.     cout << "Breadth First Traversal of the following graph is  \n";
  84.     g.BFS(a,d);
  85.  
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement