Advertisement
Guest User

Untitled

a guest
Apr 6th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.99 KB | None | 0 0
  1. /*
  2. Nama    : Difa Bagasputra Maulana
  3. NPM     : 140810180057
  4. Kelas   : A
  5. Program : BFS
  6. */
  7. #include<iostream>
  8. #include <list>
  9.  
  10. using namespace std;
  11.  
  12. // This class represents a directed graph using
  13. // adjacency list representation
  14. class Graph{
  15.     int V; // No. of vertices
  16.  
  17.     // Pointer to an array containing adjacency
  18.     // lists
  19.     list<int> *adj;
  20. public:
  21.     Graph(int V); // Constructor
  22.  
  23.     // function to add an edge to graph
  24.     void addEdge(int v, int w);
  25.  
  26.     // prints BFS traversal from a given source s
  27.     void BFS(int s);
  28. };
  29.  
  30. Graph::Graph(int V){
  31.     this->V = V;
  32.     adj = new list<int>[V];
  33. }
  34.  
  35. void Graph::addEdge(int v, int w){
  36.     adj[v].push_back(w); // Add w to v’s list.
  37. }
  38.  
  39. void Graph::BFS(int s){
  40.     // Mark all the vertices as not visited
  41.     bool *visited = new bool[V];
  42.     for(int i = 0; i < V; i++)
  43.         visited[i] = false;
  44.  
  45.     // Create a queue for BFS
  46.     list<int> queue;
  47.  
  48.     // Mark the current node as visited and enqueue it
  49.     visited[s] = true;
  50.     queue.push_back(s);
  51.  
  52.     // 'i' will be used to get all adjacent
  53.     // vertices of a vertex
  54.     list<int>::iterator i;
  55.  
  56.     while(!queue.empty()){
  57.         // Dequeue a vertex from queue and print it
  58.         s = queue.front();
  59.         cout << s << " ";
  60.         queue.pop_front();
  61.  
  62.         // Get all adjacent vertices of the dequeued
  63.         // vertex s. If a adjacent has not been visited,
  64.         // then mark it visited and enqueue it
  65.         for (i = adj[s].begin(); i != adj[s].end(); ++i){
  66.             if (!visited[*i]){
  67.                 visited[*i] = true;
  68.                 queue.push_back(*i);
  69.             }
  70.         }
  71.     }
  72. }
  73.  
  74. // Driver program to test methods of graph class
  75. int main(){
  76.     // Create a graph given in the above diagram
  77.     Graph g(8);
  78.     g.addEdge(1, 2);
  79.     g.addEdge(1, 3);
  80.     g.addEdge(2, 4);
  81.     g.addEdge(2, 5);
  82.     g.addEdge(2, 3);
  83.     g.addEdge(3, 7);
  84.     g.addEdge(3, 8);
  85.     g.addEdge(4, 5);
  86.     g.addEdge(5, 3);
  87.     g.addEdge(5, 6);
  88.     g.addEdge(7, 8);
  89.  
  90.     cout << "Breadth First Traversal ";
  91.     cout << "(mulai dari vertex 1) \n";
  92.     g.BFS(1);
  93.  
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement