fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. Scanner sc = new Scanner(System.in);
  13. int n = sc.nextInt();
  14. int m = sc.nextInt();
  15. List<List<Integer>> adj = new ArrayList<>(n);
  16.  
  17. for(int i=0;i<=n;i++){
  18. adj.add(new ArrayList<>());
  19. }
  20. System.out.println(adj);
  21. for(int i=0;i<m;i++){
  22. int u=sc.nextInt();
  23. int v = sc.nextInt();
  24. adj.get(u).add(v);
  25. adj.get(v).add(u);
  26.  
  27. }
  28. bfs(adj,1);
  29. }
  30. public static void bfs(List<List<Integer>> adj,int src){
  31. List<Integer> ans = new ArrayList<>();
  32. Queue<Integer> q = new LinkedList<>();
  33. boolean visited[] = new boolean[adj.size()];
  34. int level[] = new int[adj.size()];
  35. q.add(src);
  36. visited[src] = true;
  37. level[src] = 0;
  38.  
  39. while(!q.isEmpty()){
  40. int cur = q.poll();
  41. ans.add(cur);
  42.  
  43. for(int x : adj.get(cur)){
  44. if(!visited[x]){
  45. visited[x] = true;
  46. q.add(x);
  47. level[x] = level[cur]+1;
  48. }
  49. }
  50. }
  51.  
  52. System.out.println(ans);
  53. System.out.println("Level -->"+Arrays.toString(level));
  54. }
  55. }
Success #stdin #stdout 0.14s 60768KB
stdin
7
6
1 2
1 3
1 4
1 5
3 6
4 7
stdout
[[], [], [], [], [], [], [], []]
[1, 2, 3, 4, 5, 6, 7]
Level -->[0, 0, 1, 1, 1, 1, 2, 2]