1. class iPair{
  2. int first, second;
  3. public iPair(int first, int second)
  4. {
  5. this.first = first;
  6. this.second = second;
  7. }
  8. }
  9.  
  10. class Pair
  11. {
  12. int distance, node;
  13. public Pair(int distance, int node)
  14. {
  15. this.distance = distance;
  16. this.node = node;
  17. }
  18. }
  19.  
  20. class Solution {
  21. public List<Integer> shortestPath(int n, int m, int edges[][]) {
  22.  
  23. // Step-1 create an adjacency list
  24. ArrayList<ArrayList<iPair>> adj = new ArrayList<>();
  25. for(int i=0;i<=n;i++)
  26. {
  27. adj.add(new ArrayList<iPair>());
  28. }
  29.  
  30. for(int[] edge : edges)
  31. {
  32. int u = edge[0];
  33. int v = edge[1];
  34. int w = edge[2];
  35. adj.get(u).add(new iPair(v,w));
  36. adj.get(v).add(new iPair(u, w));
  37. }
  38.  
  39. // Step-2 Create a distance array and parent node array
  40. int[] distance = new int[n+1];
  41. int[] parent = new int[n+1];
  42. for(int i=0;i<=n;i++)
  43. {
  44. distance[i] = (int)1e9;
  45. parent[i] = i;
  46. }
  47. distance[1] = 0;
  48.  
  49. // Step-3 Store the nodes into MIN-HEAP accoriding to node's weight
  50. PriorityQueue<Pair> pq = new PriorityQueue<Pair>((x,y) -> Integer.compare(x.distance, y.distance));
  51. pq.add(new Pair(0, 1));
  52.  
  53. // Step-4 Traverse the nodes present in min-heap
  54. while(pq.size()!=0)
  55. {
  56. Pair pair = pq.poll();
  57. int currentNode = pair.node;
  58. int currentDist = pair.distance;
  59.  
  60. for(iPair neighbour : adj.get(currentNode))
  61. {
  62. int adjNode = neighbour.first;
  63. int weight = neighbour.second;
  64.  
  65. if(distance[adjNode] > (currentDist + weight))
  66. {
  67. distance[adjNode] = currentDist + weight;
  68. pq.add(new Pair(distance[adjNode], adjNode));
  69. parent[adjNode] = currentNode;
  70. }
  71. }
  72. }
  73.  
  74. List<Integer> arr = new ArrayList<>();
  75. if(distance[n] == 1e9)
  76. {
  77. arr.add(-1);
  78. return arr;
  79. }
  80.  
  81. // Backtrack from destination to source
  82. int node = n;
  83. // Use the parent[] array to trace back the path
  84. /**
  85.   * If path is:
  86.   1 → 2 → 4 → 5
  87.  
  88.   Then:
  89.   parent[5] = 4
  90.   parent[4] = 2
  91.   parent[2] = 1
  92.   parent[1] = 1
  93.  
  94.   Loop will:
  95.   add 5
  96.   add 4
  97.   add 2
  98.   (stop at 1 because parent[1] == 1)
  99.   **/
  100. while(parent[node] != node)
  101. {
  102. arr.add(node);
  103. node = parent[node];
  104. }
  105. // Because the loop stops before adding node 1, we add it explicitly.
  106. arr.add(1);
  107. // Add total distance
  108. arr.add(distance[n]);
  109.  
  110. Collections.reverse(arr);
  111. return arr;
  112. }
  113. }