Advertisement
vaibhav1906

BFS Solution

Jul 27th, 2021
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  1. //Link to the question : https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/1
  2.  
  3. class Solution
  4. {
  5. public:
  6. //Function to return Breadth First Traversal of given graph.
  7. vector<int>bfsOfGraph(int V, vector<int> adj[])
  8. {
  9.  
  10. vector<bool> visit(V,false);
  11. vector<int>ans;
  12. queue<int>q;
  13. q.push(0);
  14.  
  15. while(q.size()!=0){
  16. int curr = q.front();
  17. q.pop();
  18. ans.push_back(curr);
  19. for(int i = 0; i<adj[curr].size(); i++){
  20. int ncurr = adj[curr][i];
  21. if(visit[ncurr]==false){
  22. q.push(ncurr);
  23. visit[ncurr] = true;
  24. }
  25. }
  26. }
  27.  
  28. return ans;
  29.  
  30. }
  31. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement