fork download
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. class Main {
  5. public static void main(String[] args) {
  6. Scanner sc = new Scanner(System.in);
  7. int t = sc.nextInt();
  8.  
  9. while (t-- > 0) {
  10. int n = sc.nextInt();
  11. int e = sc.nextInt();
  12.  
  13. List<List<Integer>> adj=new ArrayList<>();
  14. for(int i=0;i<=n;i++)
  15. adj.add(new ArrayList<>());
  16.  
  17.  
  18. for (int k = 0; k < e; k++) {
  19. int u = sc.nextInt();
  20. int v = sc.nextInt();
  21. adj.get(u).add(v);
  22. adj.get(v).add(u);
  23. }
  24.  
  25. int visited[]=new int[n+1];
  26. int level[]=new int[n+1];
  27. Queue<Integer> q=new LinkedList<>();
  28.  
  29. q.add(1);
  30. visited[1]=1;
  31. level[1]=0;
  32.  
  33.  
  34. while(!q.isEmpty())
  35. {
  36. int temp=q.poll();
  37. System.out.print(temp+" ");
  38. for(int neighbour:adj.get(temp))
  39. {
  40. if(visited[neighbour]==0)
  41. {
  42. q.add(neighbour);
  43. visited[neighbour]=1;
  44. level[neighbour]=level[temp]+1;
  45. }
  46. }
  47.  
  48. }
  49. System.out.println();
  50.  
  51. for(int i=1;i<=n;i++)
  52. System.out.println(i+" "+level[i]);
  53.  
  54. }
  55. }
  56. }
Success #stdin #stdout 0.24s 58860KB
stdin
1
4 5
1 2
1 3
2 3
3 4
4 1
stdout
1 2 3 4 
1 0
2 1
3 1
4 1