Advertisement
Guest User

bfs

a guest
Feb 19th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. int main()
  2. {
  3. int t=Int;
  4. while(t--){
  5. int n=Int,m=Int;//n=node numbers & m=edges
  6. vector<int>adj[n+1];
  7. for(int a=1;a<=m;a++){
  8. int b=Int,c=Int;
  9. if(b>c)swap(b,c);
  10. adj[b].pushv(c);
  11. }
  12. int distance[n+1]={0},color[n+1]={white};
  13. queue<int>bfs;
  14. bfs.push(1);
  15. color[1]=grey;
  16. while(!bfs.empty()){
  17. int frnt=bfs.front();
  18. for(int b=0;b<adj[frnt].size();b++){
  19. int u=frnt,v=adj[frnt][b];
  20. if(color[v] == white){
  21. bfs.push(v);
  22. color[v]=grey;
  23. distance[v]=distance[u]+1;
  24. }
  25. }
  26. bfs.pop();
  27. }
  28. //for(int x=1;x<=n;x++)cout<<"distance of "<<x<<" from 1 is "<<distance[x]<<endl;
  29. cout<<distance[n]<<endl;
  30. }
  31. r0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement