shriyanshi24jindal

Cheapest Flights Within K Stops

Mar 30th, 2026
103
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 12.96 KB | None | 0 0
  1. class Pair {
  2. int stop, node, cost;
  3. public Pair(int stop, int node, int cost)
  4. {
  5. this.stop = stop;
  6. this.node = node;
  7. this.cost = cost;
  8. }
  9. }
  10.  
  11. class iPair{
  12. int first, second;
  13. public iPair(int first, int second)
  14. {
  15. this.first = first;
  16. this.second = second;
  17. }
  18. }
  19.  
  20. class Solution {
  21. public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
  22. // creating adjancency list
  23. ArrayList<ArrayList<iPair>> adj = new ArrayList<>();
  24. for(int i=0;i<n;i++)
  25. adj.add(new ArrayList<iPair>());
  26.  
  27. for(int[] edge : flights)
  28. {
  29. int u = edge[0];
  30. int v = edge[1];
  31. int w = edge[2];
  32.  
  33. adj.get(u).add(new iPair(v, w));
  34. }
  35.  
  36. // Distance array to store the updated distances from the source.
  37. int[] distance = new int[n];
  38. Arrays.fill(distance, (int)1e9);
  39. distance[src] = 0;
  40.  
  41. // Queue <stop, node, cost>
  42. Queue<Pair> q = new LinkedList<>();
  43. q.add(new Pair(0,src,0));
  44.  
  45. while(!q.isEmpty())
  46. {
  47. Pair pair = q.poll();
  48. int stop = pair.stop;
  49. int node = pair.node;
  50. int cost = pair.cost;
  51.  
  52. // We stop the process as soon as the limit for the stops reaches.
  53. if(stop>k)
  54. continue;
  55.  
  56. for(iPair neighbour : adj.get(node))
  57. {
  58. int adjNode = neighbour.first;
  59. int adjWeight = neighbour.second;
  60.  
  61. // We only update the queue if the new calculated distance
  62. // less than the prev and the stops are also within limits.
  63. if(distance[adjNode] > (cost + adjWeight) && stop <= k)
  64. {
  65. distance[adjNode] = cost + adjWeight;
  66. q.add(new Pair(stop+1, adjNode, distance[adjNode]));
  67. }
  68. }
  69. }
  70. // If the destination node is unreachable return ‘-1’
  71. // else return the calculated dist from src to dst.
  72. if(distance[dst] == Integer.MAX_VALUE)
  73. return -1;
  74. return distance[dst];
  75. }
  76. }
RAW Paste Data Copied