Advertisement
Falak_Ahmed_Shakib

Breadth First Search (aizu)

Mar 19th, 2021
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. typedef long long ll;
  4. const ll N=1000000;
  5. vector<ll>adj[N+10];
  6. bool vis[N+100];
  7. ll n,m;
  8. ll level[N+1];
  9. void BFS(ll s)
  10. {
  11. vis[s]=true;
  12.  
  13. level[s]=0;
  14.  
  15. queue<ll>q;
  16.  
  17. q.push(s);
  18.  
  19.  
  20. while(!q.empty())
  21. {
  22. ll u=q.front();
  23. q.pop();
  24.  
  25. for(ll i=0;i<adj[u].size();i++)
  26. {
  27.  
  28. if(vis[adj[u][i]]==false)
  29. {
  30. level[adj[u][i]]=level[u]+1;
  31. vis[adj[u][i]]=true;
  32. q.push(adj[u][i]);
  33.  
  34. }
  35.  
  36.  
  37. }
  38.  
  39. }
  40.  
  41.  
  42. }
  43.  
  44. int main()
  45. {
  46.  
  47. cin>>n;
  48. ll r,c,size_of_cum;
  49. for(ll i=1;i<=n;i++)
  50. {
  51. cin>>r;
  52. cin>>size_of_cum;
  53.  
  54. while(size_of_cum--)
  55. {
  56. cin>>c;
  57. adj[r].push_back(c);
  58.  
  59. }
  60. }
  61.  
  62.  
  63. BFS(1);
  64.  
  65. for(ll i=1;i<=n;i++)
  66. {
  67.  
  68. if(level[i]!=0 or i==1)cout<<i<<" "<<level[i]<<endl;
  69. else cout<<i<<" "<<-1<<endl;
  70.  
  71. }
  72.  
  73.  
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement