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 Exception {
  11.  
  12. Scanner sc = new Scanner(System.in);
  13.  
  14. int n = sc.nextInt();
  15. int m = sc.nextInt();
  16.  
  17. List<List<Integer>> adj = new ArrayList<>();
  18.  
  19. // adjacency list
  20. for(int i = 0; i <= n; i++) {
  21. adj.add(new ArrayList<>());
  22. }
  23.  
  24. // reading edges
  25. for(int i = 0; i < m; i++) {
  26.  
  27. int u = sc.nextInt();
  28. int v = sc.nextInt();
  29.  
  30. adj.get(u).add(v);
  31. adj.get(v).add(u);
  32. }
  33.  
  34. boolean visited[] = new boolean[adj.size()];
  35. int []parent = new int[adj.size()];
  36. int lvl[] = new int[adj.size()];
  37. lvl[1] = 0;
  38. dfs(1,adj,visited,parent,lvl);
  39. System.out.println(Arrays.toString(lvl));
  40. }
  41.  
  42. public static void dfs(int node,List<List<Integer>> adj,boolean []visited,int []parent,int []lvl ){
  43. System.out.println(node);
  44. visited[node] = true;
  45.  
  46. for(int x : adj.get(node)){
  47. if(!visited[x]){
  48. lvl[x] = lvl[node]+1;
  49. parent[x] = node;
  50. dfs(x,adj,visited,parent,lvl);
  51. }
  52. }
  53.  
  54.  
  55. }
  56.  
  57. }
Success #stdin #stdout 0.11s 54520KB
stdin
8
7
1 2
1 3
2 4
2 5
4 8
3 6
3 7
stdout
1
2
4
8
5
3
6
7
[0, 0, 1, 1, 2, 2, 2, 2, 3]