Rinkeshkumarsinha's blog

By Rinkeshkumarsinha, history, 15 months ago, In English

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;

}

  • Vote: I like it
  • -24
  • Vote: I do not like it