From 46dec0420b39ded22265a51684f82d44f37e85de Mon Sep 17 00:00:00 2001 From: Agam118 <87620190+Agam118@users.noreply.github.com> Date: Sat, 15 Oct 2022 20:34:05 +0530 Subject: [PATCH] Graph BFS Datastructure --- BFS | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 BFS diff --git a/BFS b/BFS new file mode 100644 index 0000000..4f4049a --- /dev/null +++ b/BFS @@ -0,0 +1,80 @@ +. +#include +using namespace std; + +class Graph +{ + int V; + + + vector> adj; +public: + Graph(int V); // Constructor + + void addEdge(int v, int w); + + + void BFS(int s); +}; + +Graph::Graph(int V) +{ + this->V = V; + adj.resize(V); +} + +void Graph::addEdge(int v, int w) +{ + adj[v].push_back(w); // Add w to v’s list. +} + +void Graph::BFS(int s) +{ + // Mark all the vertices as not visited + vector visited; + visited.resize(V,false); + + // Create a queue for BFS + list queue; + + // Mark the current node as visited and enqueue it + visited[s] = true; + queue.push_back(s); + + while(!queue.empty()) + { + + s = queue.front(); + cout << s << " "; + queue.pop_front(); + + + for (auto adjecent: adj[s]) + { + if (!visited[adjecent]) + { + visited[adjecent] = true; + queue.push_back(adjecent); + } + } + } +} + + +int main() +{ + + Graph g(4); + g.addEdge(0, 1); + g.addEdge(0, 2); + g.addEdge(1, 2); + g.addEdge(2, 0); + g.addEdge(2, 3); + g.addEdge(3, 3); + + cout << "Following is Breadth First Traversal " + << "(starting from vertex 2) \n"; + g.BFS(2); + + return 0; +}