diff --git a/Data Structure Algo/C++/bfs.cpp b/Data Structure Algo/C++/bfs.cpp index 1104c744..f7b4e17d 100644 --- a/Data Structure Algo/C++/bfs.cpp +++ b/Data Structure Algo/C++/bfs.cpp @@ -1,92 +1,56 @@ -#include -#include - +#include using namespace std; - -// This class represents a directed graph using -// adjacency list representation -class Graph + +class Solution { - int V; // No. of vertices - - // Pointer to an array containing adjacency - // lists - list *adj; -public: - Graph(int V); // Constructor - - // function to add an edge to graph - void addEdge(int v, int w); - - // prints BFS traversal from a given source s - void BFS(int s); + public: + + vectorbfsOfGraph(int V, vector adj[]) + { + + bool visited[V]={0}; + queueq; + vectorv; + q.push(0); + while(!q.empty()){ + int t=q.front(); + q.pop(); + v.push_back(t); + for(auto i=adj[t].begin();i!=adj[t].end();i++){ + if(visited[*i]==0){ + visited[*i]=1; + q.push(*i); + } + } + } + return v; + } }; - -Graph::Graph(int V) -{ - this->V = V; - adj = new list[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 - bool *visited = new bool[V]; - for(int i = 0; i < V; i++) - visited[i] = false; - - // Create a queue for BFS - list queue; - - // Mark the current node as visited and enqueue it - visited[s] = true; - queue.push_back(s); - - // 'i' will be used to get all adjacent - // vertices of a vertex - list::iterator i; - - while(!queue.empty()) - { - // Dequeue a vertex from queue and print it - s = queue.front(); - cout << s << " "; - queue.pop_front(); - - // Get all adjacent vertices of the dequeued - // vertex s. If a adjacent has not been visited, - // then mark it visited and enqueue it - for (i = adj[s].begin(); i != adj[s].end(); ++i) - { - if (!visited[*i]) - { - visited[*i] = true; - queue.push_back(*i); - } + + +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); + + } + + Solution obj; + vectorans=obj.bfsOfGraph(V, adj); + for(int i=0;i