Q25 Cheapest Flights Within K Stops - LeetCode 787

PHOTO EMBED

Fri Apr 28 2023 06:26:24 GMT+0000 (Coordinated Universal Time)

Saved by @Ayush_dabas07

class Solution {
    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
        /* Q25 , bellman ford variation 
        -> We need to use another array temp so that the distances from the previous    
        iteration stored in dist don't change. 

        if we dont do that the array is going to dynamically change with each iteration of
        inside loop and we are not going to get ith edge answers .

        */

        //making path array 
        int[] path = new int[n];
        Arrays.fill(path , Integer.MAX_VALUE);
        path[src] = 0;  //cost of src from src = 0


        //firing bellman ford for K times so we just get <= k edges answer in the path
        for(int i = 0 ;i <= k ; i++){
            
            //copying path array so it doesn't get updated dynamically but stores one 
            // iteration result in the path array 
            int temp[] = Arrays.copyOf(path , n);
            for(int[] flight : flights) {
                int u = flight[0] , v = flight[1] , wt = flight[2];

                if(path[u] == Integer.MAX_VALUE)
                continue;

                temp[v] = Math.min(temp[v] , path[u] + wt);
            }
            path = temp;
        }

        //we didnt get any answer for <= k edges 
        return path[dst] == Integer.MAX_VALUE ? -1 : path[dst];
    }
}
content_copyCOPY

https://leetcode.com/problems/cheapest-flights-within-k-stops/solutions/340911/Understanding-Bellman-Ford/