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.  
  24. adj.get(u).add(v);
  25. adj.get(v).add(u);
  26. }
  27.  
  28. shoetestPathOfIthNodeFromSrc(adj,1);
  29. }
  30.  
  31. public static void shoetestPathOfIthNodeFromSrc(List<List<Integer>> adj, int src){
  32. int n = adj.size();
  33. boolean visited[] = new boolean[n];
  34. int level[] = new int [n];
  35. int path[] = new int [n];
  36. Queue<Integer> q = new LinkedList<>();
  37. q.offer(src);
  38. level[src] = 0;
  39. path[src] = 1;
  40. visited[src] = true;
  41. while(!q.isEmpty()){
  42. int cur = q.poll();
  43.  
  44. for(int x : adj.get(cur)){
  45.  
  46. if(!visited[x]){
  47. q.add(x);
  48. level[x] = level[cur]+1;
  49. path[x] = path[cur];
  50. visited[x]=true;
  51. }else{
  52. if(level[cur]+1 == level[x]){
  53. path[x] = path[x] + path[cur];
  54. }
  55. }
  56. }
  57. }
  58. System.out.println("level :-->"+Arrays.toString(level));
  59. System.out.println("path :-->"+Arrays.toString(path));
  60. }
  61.  
  62. }
Success #stdin #stdout 0.14s 58760KB
stdin
10 11
1 2
1 3
1 4
4 8
3 6
2 5
8 9
6 7
5 10
9 10
7 10
stdout
level :-->[0, 0, 1, 1, 1, 2, 2, 3, 2, 3, 3]
path :-->[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]