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. // your code goes here
  13. }
  14. }
  15.  
  16. class TestClass {
  17. public static void main(String args[] ) throws Exception {
  18. //BufferedReader
  19. String input = br.readLine(); // Reading input from STDIN
  20. String[] arr = input.split(" ");
  21. int n = Integer.parseInt(arr[0]);
  22. int e = Integer.parseInt(arr[1]);
  23. ArrayList<ArrayList<Integer>> adj = new ArrayList<>();
  24. for(int i = 0 ; i<=n ; i++){
  25. adj.add(new ArrayList<Integer>()); //as the nodes are numbered 1 ---- n
  26. }
  27.  
  28. //unit weight undirected graph
  29. for(int i = 0 ; i<e ; i++){
  30. input = br.readLine();
  31. String[] nodes = input.split(" ");
  32. int u = Integer.parseInt(nodes[0]);
  33. int v = Integer.parseInt(nodes[1]);
  34. adj.get(u).add(v);
  35. adj.get(v).add(u);
  36. }
  37.  
  38. input = br.readLine();
  39. int source = Integer.parseInt(input);
  40. //find shortest distance of all nodes from the dource node
  41. int[] sArr = findShortestD(source , adj); //becuase nodes are 1 based
  42. for(int i = 1 ; i< sArr.length ; i++){
  43. System.out.print(sArr[i]+ " ");
  44. }
  45. }
  46.  
  47. private static int[] findShortestD(int s , ArrayList<ArrayList<Integer>> adj){
  48. int n = adj.size();
  49. int[] dist = new int[n];
  50. Arrays.fill(dist , Integer.MAX_VALUE);
  51. dist[s] = 0;
  52. Queue<Integer> q = new LinkedList<>();
  53. q.offer(s);
  54.  
  55. while(!q.isEmpty()){
  56. int top = q.poll();
  57. for(int neigh : adj.get(top)){
  58. int distTon = dist[top] + 1;
  59. if(distTon < dist[neigh]){
  60. q.offer(neigh);
  61. dist[neigh] = dist[top] + 1;
  62. }
  63. }
  64. }
  65. return dist;
  66. }
  67.  
  68. }
  69.  
Success #stdin #stdout 0.08s 54672KB
stdin
Standard input is empty
stdout
Standard output is empty