Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- void addEdge(vector<int> adj[], int u, int v)
- {
- adj[u].push_back(v);
- }
- void bfs(vector<int> adj[], int V, int start)
- {
- //Code here
- queue<int> q;
- vector<int> vis(V,0);
- vis[start]=1;
- q.push(start);
- while(!q.empty())
- {
- int v=q.front();
- cout<<v<<" ";
- q.pop();
- for(int x:adj[v])
- {
- if(vis[x]==0)
- {
- vis[x]=1;
- q.push(x);
- }
- }
- }
- }
- void printGraph(vector<int> adj[], int V)
- {
- for (int v = 0; v < V; ++v)
- {
- cout << "Adjacency list of vertex "
- << v << "\n";
- for (auto x : adj[v])
- cout << x <<" ";
- cout<<"\n";
- }
- }
- int main()
- {
- int V = 4;
- vector<int> adj[V];
- addEdge(adj,0, 1);
- addEdge(adj,0, 2);
- addEdge(adj,1, 2);
- addEdge(adj,2, 0);
- addEdge(adj,2, 3);
- addEdge(adj,3, 3);
- printGraph(adj,V);
- bfs(adj, V, 2);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement