Skip to content

Commit

Permalink
Added solution - LeetHub
Browse files Browse the repository at this point in the history
  • Loading branch information
sainikcodes24x7 committed Jul 2, 2023
1 parent 846f67a commit a9faa21
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions BFS of graph - GFG/bfs-of-graph.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

// } Driver Code Ends
class Solution {
public:
// Function to return Breadth First Traversal of given graph.
vector<int> bfsOfGraph(int V, vector<int> adj[]) {
// Code here
queue<int>q;
vector<int>ans;
vector<int>vis(V+1,0);
vis[0]=1;
q.push(0);
while(!q.empty()){
auto top=q.front();
q.pop();
ans.push_back(top);
for(auto nbr:adj[top]){
if(!vis[nbr]){
vis[nbr]=1;
q.push(nbr);
}
}
}
return ans;
}
};

//{ Driver Code Starts.
int main() {
int tc;
cin >> tc;
while (tc--) {
int V, E;
cin >> V >>

E;

vector<int> 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;
vector<int> ans = obj.bfsOfGraph(V, adj);
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
return 0;
}
// } Driver Code Ends

0 comments on commit a9faa21

Please sign in to comment.