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