BFS GRAPH SHOWING ADJACENCY LIST REPRESENTATION

Revision en1, by Rinkeshkumarsinha, 2023-10-01 13:39:36

BFS

void bfs(int s,vectoradj[],int V){

int n=V;
queue<int>q;
q.push(s);
vector<int>visited(n,0);
visited[s]=1;
while(!q.empty()){
    auto node=q.front();
    cout<<node;
    q.pop();
    for(auto it:adj[node]){
        if(!visited[it]){
            visited[it]=1;
            q.push(it);
        }
    }

}

return;

}

int main(){

int V;
int E;
cin>>V>>E;//V is no of vertices and E is no of Edges
vector<int>adj[V+1];
for(int i=0;i<E;i++){
    int u,v;
    cin>>u>>v;
    adj[u].push_back(v);
    adj[v].push_back(u);
}

cout<<"please enter the source node";
int s;
cin>>s;
bfs(s,adj,V);

return 0;

}

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English Rinkeshkumarsinha 2023-10-01 13:39:36 908 Initial revision (published)