We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<cmath>#include<cstdio>#include<vector>#include<iostream>#include<algorithm>#include<queue>usingnamespacestd;voidBFS(vector<int>adj[],intvisited[],ints){queue<int>Q;Q.push(s);visited[s]=0;while(!Q.empty()){intnode=Q.front();Q.pop();for(inti=0;i<adj[node].size();++i){if(visited[adj[node][i]]==-1){visited[adj[node][i]]=0;visited[adj[node][i]]=6+visited[node];Q.push(adj[node][i]);// Pushing all the neighbouring nodes to the queue}}}}intmain(){/* Enter your code here. Read input from STDIN. Print output to STDOUT */intq;cin>>q;for(inti=0;i<q;++i){intn,m,u,v,s;cin>>n>>m;vector<int>adj[n+1];for(intj=1;j<=m;++j){cin>>u>>v;adj[u].push_back(v);adj[v].push_back(u);}cin>>s;intvisited[n+1];for(inti=1;i<=n;++i)visited[i]=-1;BFS(adj,visited,s);for(inti=1;i<=n;++i){if(visited[i]!=0)cout<<visited[i]<<" ";}cout<<endl;}return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
BFS: Shortest Reach in a Graph
You are viewing a single comment's thread. Return to all comments →
Below is the simple C++ solution