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<>();
  16. for(int i=0; i<=n;i++){
  17. adj.add(new ArrayList<>());
  18. }
  19.  
  20. for(int i=0; i<m; i++){
  21. int u = sc.nextInt();
  22. int v = sc.nextInt();
  23. adj.get(u).add(v);
  24. adj.get(v).add(u);
  25. }
  26. int []parent = new int[adj.size()];
  27. int []height = new int[adj.size()];
  28. boolean []visited = new boolean[adj.size()];
  29. heightOfEachNode(1,adj,parent,visited,height);
  30. System.out.println(Arrays.toString(height));
  31.  
  32. }
  33.  
  34. public static void heightOfEachNode(int node,List<List<Integer>> adj,int[] par,boolean[] vis,int []height){
  35. vis[node] = true;
  36.  
  37. for(int x: adj.get(node)){
  38. if(vis[x] == false){
  39. par[x] = node;
  40. heightOfEachNode(x,adj,par,vis,height);
  41. }
  42. }
  43. int h =0;
  44. for(int child: adj.get(node)){
  45. if(child == par[node]){
  46. // it's parent node , we have to traverse all children of child node
  47. }else{
  48. h = Math.max(h,height[child]);
  49. }
  50. }
  51.  
  52. height[node] = h+1;
  53.  
  54.  
  55.  
  56. }
  57. }
Success #stdin #stdout 0.13s 54604KB
stdin
7
6
1 2
1 3
2 4
2 5
3 6
3 7
stdout
[0, 3, 2, 2, 1, 1, 1, 1]