Advertisement
Falak_Ahmed_Shakib

bfs pb 2 Breadth First Search Shortest Reach

Mar 19th, 2021
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 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]+6;
  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.  
  48. ll t;
  49.  
  50. cin>>t;
  51.  
  52. while(t--)
  53. {
  54. cin>>n>>m;
  55.  
  56. ll a,b;
  57. for(ll i=0;i<m;i++)
  58. {
  59. cin>>a>>b;
  60.  
  61. adj[a].push_back(b);
  62.  
  63. adj[b].push_back(a);
  64.  
  65. }
  66.  
  67.  
  68.  
  69. ll s;
  70. cin>>s;
  71. BFS(s);
  72.  
  73. for(ll i=1;i<=n;i++)
  74. {
  75. if(s==i)continue;
  76.  
  77. if(level[i])cout<<level[i]<<" ";
  78. else cout<<-1<<" ";
  79. }cout<<endl;
  80.  
  81. for(ll i=1;i<=n;i++)
  82. {
  83. level[i]=0;
  84. adj[i].clear();
  85. vis[i]=false;
  86. }
  87.  
  88. }
  89.  
  90.  
  91.  
  92. }
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement