fork download
  1. #include <iostream>
  2. using namespace std;
  3. #include <bits/stdc++.h>
  4.  
  5. int main() {
  6. // your code goes here
  7. int n,m;
  8. cin>>n>>m;
  9. vector<int>b[n+5];
  10. int i=1;
  11. for(i=1;i<=m;i++)
  12. {
  13. int x,y;
  14. cin>>x>>y;
  15. b[x].push_back(y);
  16. b[y].push_back(x);
  17. }
  18.  
  19. int source = 1;
  20. int used[n+5]={0};
  21. int level[n+5]={-1};
  22. queue<int>q;
  23. q.push(source);
  24. used[source]=1;
  25. level[source]=0;
  26.  
  27. while(!q.empty())
  28. {
  29. int removed;
  30. removed=q.front();
  31. q.pop();
  32.  
  33. for(auto x:b[removed])
  34. {
  35. if(used[x]==0)
  36. {
  37. q.push(x);
  38. used[x]=1;
  39. level[x]=level[removed]+1;
  40. }
  41. }
  42.  
  43.  
  44. }
  45.  
  46. i=1;
  47. while(i<=n)
  48. {
  49. if(used[i]==0)
  50. {
  51. cout<<"you cannot reach node "<<i<<" to source node "<<source<<endl;
  52. }
  53. else
  54. {
  55. cout<<"you can reach node "<<i<<" to source node "<<source<<endl;
  56. }
  57. //cout<<i<<"-"<<level[i]<<endl;
  58. i++;
  59.  
  60. }
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0s 5288KB
stdin
7 7
1 2
1 3
1 4
2 5
3 5
3 6
4 6
stdout
you can reach node 1 to source node 1
you can reach node 2 to source node 1
you can reach node 3 to source node 1
you can reach node 4 to source node 1
you can reach node 5 to source node 1
you can reach node 6 to source node 1
you cannot reach node 7 to source node 1