fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. const int N=100067;
  6.  
  7. vector<int> adj[N];
  8. int odl[N];
  9.  
  10.  
  11.  
  12. void bfs(int n){
  13.  
  14.  
  15. for(int i=0; i<N; i++)
  16. odl[i]=-1;
  17. odl[n]=0;
  18.  
  19. queue<int> kol;
  20. kol.push(n);
  21. while(!kol.empty()){
  22. int a=kol.front();
  23. kol.pop();
  24. for(int o: adj[a]){
  25. if(odl[o]==-1){
  26. odl[o]=odl[a]+1;
  27. kol.push(o);}
  28. }
  29.  
  30.  
  31.  
  32.  
  33.  
  34. }
  35.  
  36.  
  37. }
  38.  
  39.  
  40.  
  41. int main() {
  42. ios_base::sync_with_stdio(0);
  43. cin.tie(0);
  44.  
  45. int n,m,a,b;
  46. cin>>n>>m;
  47. for(int i=0; i<m; i++)
  48. {
  49. cin>>a>>b;
  50. adj[a].push_back(b);
  51. adj[b].push_back(a);}
  52.  
  53.  
  54. bfs(1);
  55.  
  56. for(int i=1; i<n+1; i++)
  57. cout<<odl[i]<<" ";
  58.  
  59.  
  60.  
  61. return 0;
  62. }
Success #stdin #stdout 0.01s 6320KB
stdin
6 5
1 2
6 4
1 4
3 5
2 4
stdout
0 1 -1 1 -1 2