jayati

BFS

Sep 2nd, 2023
1,018
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. //{ Driver Code Starts
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. // } Driver Code Ends
  6. class Solution {
  7.   public:
  8.     // Function to return Breadth First Traversal of given graph.
  9.     vector<int> bfsOfGraph(int V, vector<int> adj[]) {
  10.         // Code here
  11.         int vis[V]={0};
  12.         vis[0]=1;
  13.        
  14.         vector<int> bfs;
  15.         queue<int> q;
  16.         q.push(0);
  17.         while(!q.empty())
  18.         {
  19.             int node= q.front();
  20.             q.pop();
  21.             bfs.push_back(node);
  22.             for(auto u:adj[node])
  23.             {
  24.                 if(!vis[u])
  25.                 {
  26.                     vis[u]=1;
  27.                     q.push(u);
  28.                 }
  29.             }
  30.         }
  31.         return bfs;
  32.     }
  33. };
  34.  
  35. //{ Driver Code Starts.
  36. int main() {
  37.     int tc;
  38.     cin >> tc;
  39.     while (tc--) {
  40.         int V, E;
  41.         cin >> V >>
  42.  
  43.             E;
  44.  
  45.         vector<int> adj[V];
  46.  
  47.         for (int i = 0; i < E; i++) {
  48.             int u, v;
  49.             cin >> u >> v;
  50.             adj[u].push_back(v);
  51.             //      adj[v].push_back(u);
  52.         }
  53.         // string s1;
  54.         // cin>>s1;
  55.         Solution obj;
  56.         vector<int> ans = obj.bfsOfGraph(V, adj);
  57.         for (int i = 0; i < ans.size(); i++) {
  58.             cout << ans[i] << " ";
  59.         }
  60.         cout << endl;
  61.     }
  62.     return 0;
  63. }
  64. // } Driver Code Ends
  65. // https://practice.geeksforgeeks.org/problems/bfs-traversal-of-graph/
Advertisement
Add Comment
Please, Sign In to add comment