#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

vector<int> bfs(int start, int n, vector<int> adj[]){
    vector<int> bfsV;
    vector<int> vis(n,0);
    queue<int> q;
    
    vis[start]=1;
    q.push(start);
    
    while(!q.empty()){
        int node=q.front();
        q.pop();
        bfsV.push_back(node);
        for(auto neighbour : adj[node]){
            if(vis[neighbour]==0){
                vis[neighbour]=1;
                q.push(neighbour);
            }
        }
    }
    return bfsV;
}

int main(){
    int n=5;
    vector<int> adj[5];
    adj[0] = {1, 2};
    adj[1] = {0, 3};
    adj[2] = {0, 4};
    adj[3] = {1};
    adj[4] = {2};

    cout<<"Printing Adjacency List:\n";
    for(int i=0;i<n;i++){
        cout<<"Node of "<<i<<" : ";
        for(auto it:adj[i]){
            cout<<it<<" ";
        }
        cout<<"\n";
    }
    
    vector<int> bfsV;
    bfsV=bfs(0,n,adj);
    cout<<"BFS traversal\n";
    for(auto i : bfsV){
        cout<<i<<" ";
    }
    return 0;
}

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: