thewitchking

Untitled

Apr 27th, 2026
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
  2.         List<List<int[]>> adj = new ArrayList<>();
  3.         for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
  4.         for (int[] flight : flights) {
  5.             adj.get(flight[0]).add(new int[] {flight[1], flight[2]});
  6.         }
  7.         Queue<int[]> q = new LinkedList<>();
  8.         q.offer(new int[] {src, 0});
  9.         int[] minCost = new int[n];
  10.         Arrays.fill(minCost, Integer.MAX_VALUE);
  11.         int stops = 0;
  12.         while (!q.isEmpty() && stops <= k) {
  13.             int size = q.size();
  14.             while (size-- > 0) {
  15.                 int[] curr = q.poll();
  16.                 for (int[] neighbour : adj.get(curr[0])) {
  17.                     int price = neighbour[1], neighbourNode = neighbour[0];
  18.                     if (price + curr[1] >= minCost[neighbourNode]) continue;
  19.                     minCost[neighbourNode] = price + curr[1];
  20.                     q.offer(new int[] {neighbourNode, minCost[neighbourNode]});
  21.                 }
  22.             }
  23.             stops++;
  24.         }
  25.         return minCost[dst] == Integer.MAX_VALUE ? -1 : minCost[dst];
  26.     }
Advertisement
Add Comment
Please, Sign In to add comment