The Indian Engineer

Problem 787 Cheapest Flights Within K Stops

Posted on Last edited 4 mins

Dijkstras Graph Shortest-Path Greedy

Problem Statement

Link - Problem 787

Question

There are n cities connected by some number of flights. You are given an array flights where flights[i] = [fromi, toi, pricei] indicates that there is a flight from city fromi to city toi with cost pricei.

You are also given three integers src, dst, and k, return the cheapest price from src to dst with at most k stops. If there is no such route, return -1.

Example 1

image1

Input: n = 4, flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]], src = 0, dst = 3, k = 1
Output: 700
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 3 is marked in red and has cost 100 + 600 = 700.
Note that the path through cities [0,1,2,3] is cheaper but is invalid because it uses 2 stops.

Example 2

image2

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph is shown above.
The optimal path with at most 1 stop from city 0 to 2 is marked in red and has cost 100 + 100 = 200.

Example 3

image3

Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph is shown above.
The optimal path with no stops from city 0 to 2 is marked in red and has cost 500.

Constraints

Solution

class Solution {
public:
    int dijkstras(int src, vector<vector<pair<int,int>>>&adj, int target, int k,int n){
        vector<int>dist(n+1,INT_MAX);
        vector<int>stops(n+1,INT_MAX);

        dist[src]=0;
        stops[src]=0;

        priority_queue<vector<int>,vector<vector<int>>,greater<vector<int>>>pq;

        pq.push({0,src,0});
        while(!pq.empty()){
            auto vec = pq.top();
            pq.pop();
            if(target == vec[1])
                return vec[0];
            if(vec[2]==k+1)
                continue;

            for(auto it:adj[vec[1]]){
                if(vec[0]+it.second<dist[it.first] || vec[2]+1<stops[it.first]){
                    dist[it.first] = it.second + vec[0];
                    stops[it.first] = vec[2]+1;
                    pq.push({dist[it.first],it.first,stops[it.first]});
                }
            }
        }
        return -1;
    }
    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) {
        vector<vector<pair<int,int>>>adj(n+1);
        for(auto it: flights){
            adj[it[0]].push_back({it[1],it[2]});
        }

        return dijkstras(src,adj,dst,k,n);
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Dijsktras O(nlogn) O(n)

Explanation

1. Intuition

2. Implementation