fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. using namespace std;
  5. int N, M = 0;
  6. vector<int> map[21];
  7. int visit[21];
  8. int dis[21];
  9. queue<int> q;
  10.  
  11. void BFS()
  12. {
  13. while(!q.empty())
  14. {
  15. int current = q.front(); q.pop();
  16. for(int i = 0; i < map[current].size(); i++)
  17. {
  18. int next = map[current][i];
  19. if(visit[next] == 0)
  20. {
  21. visit[next] = 1;
  22. dis[next] = dis[current]+1;
  23. q.push(next);
  24. }
  25. }
  26. }
  27. }
  28.  
  29. int main() {
  30. // your code goes here
  31. int a,b = 0;
  32. cin >> N >> M;
  33. for(int i = 0 ; i < M; i++)
  34. {
  35. cin >> a >> b;
  36. map[a].push_back(b);
  37. }
  38. visit[1] = 1;
  39. q.push(1);
  40. BFS();
  41. for(int i = 2; i<=N; i++){
  42. cout << i <<" : " << dis[i] << endl;;
  43. }
  44. return 0;
  45. }
Success #stdin #stdout 0s 4520KB
stdin
6 9
1 3
1 4
2 1
2 5
3 4
4 5
4 6
6 2
6 5
stdout
2 : 3
3 : 1
4 : 1
5 : 2
6 : 2