Advertisement
vaibhav1906

BFS

Jan 4th, 2022
1,096
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. void addEdge(vector<int> adj[], int u, int v)
  5. {
  6.     adj[u].push_back(v);
  7. }
  8. void bfs(vector<int> adj[], int V, int start)
  9. {
  10.     //Code here
  11.     queue<int> q;
  12.     vector<int> vis(V,0);
  13.     vis[start]=1;
  14.     q.push(start);
  15.     while(!q.empty())
  16.     {
  17.         int v=q.front();
  18.         cout<<v<<" ";
  19.         q.pop();
  20.         for(int x:adj[v])
  21.         {
  22.             if(vis[x]==0)
  23.             {
  24.                 vis[x]=1;
  25.                 q.push(x);
  26.             }
  27.         }
  28.     }
  29. }
  30.  
  31. void printGraph(vector<int> adj[], int V)
  32. {
  33.     for (int v = 0; v < V; ++v)
  34.     {
  35.         cout << "Adjacency list of vertex "
  36.              << v << "\n";
  37.         for (auto x : adj[v])
  38.            cout << x <<" ";
  39.         cout<<"\n";
  40.     }
  41. }
  42. int main()
  43. {
  44.     int V = 4;
  45.     vector<int> adj[V];
  46.     addEdge(adj,0, 1);
  47.     addEdge(adj,0, 2);
  48.     addEdge(adj,1, 2);
  49.     addEdge(adj,2, 0);
  50.     addEdge(adj,2, 3);
  51.     addEdge(adj,3, 3);
  52.     printGraph(adj,V);
  53.     bfs(adj, V, 2);
  54.     return 0;
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement