From 8d172d19a8d7aec08252f4d6571bff6215e62184 Mon Sep 17 00:00:00 2001 From: SWARAJ D SHELAVALE <47442263+SwarajShelavale@users.noreply.github.com> Date: Sun, 9 Oct 2022 22:05:08 +0530 Subject: [PATCH] Added Code for BFS of Graph --- BFS of Graph.cpp | 62 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 BFS of Graph.cpp diff --git a/BFS of Graph.cpp b/BFS of Graph.cpp new file mode 100644 index 0000000..98deafe --- /dev/null +++ b/BFS of Graph.cpp @@ -0,0 +1,62 @@ +//BFS of Graph + +#include +using namespace std; + +class Solution +{ + public: + //Function to return Breadth First Traversal of given graph. + vectorbfsOfGraph(int V, vector adj[]) + { + // Code here4 + vectorv; + vectorvisited(V,0); + queueq; + q.push(0); + visited[0]=1; + while(!q.empty()) + { + int u=q.front(); + q.pop(); + v.push_back(u); + for(auto x:adj[u]) + { + if(visited[x]==0) + { + visited[x]=1; + q.push(x); + } + } + } + return v; + } +}; + +int main(){ + int tc; + cin >> tc; + while(tc--){ + int V, E; + cin >> V >> E; + + vector adj[V]; + + for(int i = 0; i < E; i++) + { + int u, v; + cin >> u >> v; + adj[u].push_back(v); + // adj[v].push_back(u); + } + // string s1; + // cin>>s1; + Solution obj; + vectorans=obj.bfsOfGraph(V, adj); + for(int i=0;i