fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int main() {
  5.  
  6. int n;
  7. cin>>n;
  8. int e;
  9. cin>>e;
  10.  
  11. vector<int> g[n+1];
  12.  
  13. for(int i=1; i<=e; i++){
  14. int u,v;
  15. cin>>u;
  16. cin>>v;
  17. g[u].push_back(v);
  18. g[v].push_back(u);
  19. }
  20.  
  21. int source;
  22. cin>>source;
  23.  
  24. // solution;
  25.  
  26. queue<int> q;
  27.  
  28. q.push(source);
  29.  
  30. vector<int> record (n+1,-1);
  31. record[source]=0;
  32.  
  33. while(!q.empty()){
  34.  
  35. int t = q.front();
  36.  
  37. q.pop();
  38.  
  39. for(auto x: g[t]){
  40.  
  41. if(record[x]<0){
  42. q.push(x);
  43. record[x] = record[t]+1;
  44. }
  45. }
  46.  
  47. }
  48.  
  49. for(int i=1; i<=n; i++){
  50. cout<< record[i]<< " ";
  51. }
  52.  
  53. return 0;
  54. }
Success #stdin #stdout 0.01s 5288KB
stdin
7 1
1 2
2 3
3 6
4 5
5 1
4 7
4 6
stdout
1 0 -1 -1 -1 -1 -1