fork download
  1. #include <iostream>
  2. using namespace std;
  3. #include<vector>
  4. #include <bits/stdc++.h>
  5. int main() {
  6. // your code goes here
  7. int n,m;
  8. cin>>n>>m;
  9. vector<int>g[n+5];
  10.  
  11. int x,y;
  12. for(int i=1;i<=m;i++)
  13. {
  14. cin>>x>>y;
  15. g[x].push_back(y);
  16. g[y].push_back(x);
  17. }
  18. int source=1;
  19. int used[n+5]={0};
  20. int level[n+5]={0};
  21. queue<int>q;
  22. q.push(source);
  23. used[source]=1;
  24. level[source]=0;
  25. while(!q.empty())
  26. {
  27. int removed;
  28. removed = q.front();
  29. cout<<removed<<"-"<<level[removed]<<endl;
  30. q.pop();
  31.  
  32. for(auto x:g[removed])
  33. {
  34. if(used[x]==0)
  35. {
  36. q.push(x);
  37. }
  38. used[x]=1;
  39. level[x]=level[removed]+1;
  40.  
  41. }
  42.  
  43. }
  44. i=1;
  45. //while(i<=n) For each input graph print the shortest distance of each node from the source node.
  46. //{ serial wise...
  47. // cout<<level[i]<<" ";
  48. //}
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0.01s 5288KB
stdin
7 8
1 5 
1 3
1 4
1 2
3 6
4 6
2 10
6 9
stdout
1-0
5-1
3-1
4-1
2-1
6-2
10-2
9-3