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. {
  53. if(visited[i]==0)
  54. System.out.println("we cant reach the source node to "+i);
  55. else
  56. System.out.println("we can reach the source node to "+i);
  57.  
  58. }
  59.  
  60. }
  61. }
  62. }
Success #stdin #stdout 0.17s 60912KB
stdin
1
6 4
1 2
1 3
4 5
5 6
stdout
1 2 3 
we can reach the source node to 1
we can reach the source node to 2
we can reach the source node to 3
we cant reach the source node to 4
we cant reach the source node to 5
we cant reach the source node to 6