-
Notifications
You must be signed in to change notification settings - Fork 55
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
846f67a
commit a9faa21
Showing
1 changed file
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |