fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int main() {
  5. int n, m;
  6. cin>>n>>m;
  7. vector<int> adjList[n];
  8. for(int i=0;i<m;i++){
  9. int x,y;
  10. cin>>x>>y;
  11. adjList[x].push_back(y);
  12. adjList[y].push_back(x);
  13. }
  14.  
  15. int source=1;
  16. vector<int> visited(n, 0);
  17. vector<int> level(n, 0);
  18. queue<int> q;
  19. q.push(source);
  20. visited[source]=1;
  21. while(!q.empty()){
  22. int node=q.front();
  23. cout<<node<<" "<<level[node]<<"\n";
  24. q.pop();
  25. visited[node]=1;
  26. for(auto adjNode : adjList[node]){
  27. if(!visited[adjNode]){
  28. q.push(adjNode);
  29. visited[adjNode]=1;
  30. level[adjNode]=level[node]+1;
  31. }
  32. }
  33. }
  34. return 0;
  35. }
Success #stdin #stdout 0s 5292KB
stdin
6 8
0 1
1 2
2 3
3 4
4 5
0 3
1 4
2 5
stdout
1 0
0 1
2 1
4 1
3 2
5 2