← Home

787. Cheapest Flights Within K Stops

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
heap / priority queueC++Markdown
787

This is one of those problems where the clean idea matters more than the amount of code. For 787. Cheapest Flights Within K Stops, the solution in this repository is mainly a heap / priority queue solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: heap / priority queue.

The notes already sitting in the source point us in the right direction:

  • Single-Source Shortest Path:Bellman-Ford Algorithm
  • https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/115596/c%2B%2B-8-line-bellman-ford

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are findCheapestPrice, dist, tmp.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The heap keeps the best candidate available without sorting the whole world every time.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Single-Source Shortest Path:Bellman-Ford Algorithm
02//Runtime: 36 ms, faster than 74.30% of C++ online submissions for Cheapest Flights Within K Stops.
03//Memory Usage: 10.9 MB, less than 72.65% of C++ online submissions for Cheapest Flights Within K Stops.
04//https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/115596/c%2B%2B-8-line-bellman-ford
05class Solution {
06public:
07    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
08        /*
09        n: [1, 100]
10        price: [1, 10000]
11        */
12        int MAX = 1e6+1;
13        vector<int> dist(n, MAX);
14        
15        //base case
16        dist[src] = 0;
17        for(vector<int>& flight : flights){
18            //whether use flight[0] as middle point
19            if(flight[0] == src)
20                dist[flight[1]] = flight[2];
21        }
22        
23        //relax for K times
24        while(K-- > 0){
25            // cout << "=============" << endl;
26            //relax
27            vector<int> tmp(dist);
28            for(vector<int>& flight : flights){
29                //whether use flight[0] as middle point
30                /*
31                tmp cannot depend on itself!
32                it must be calculated from "dist"(from previous iteration!)
33                */
34                tmp[flight[1]] = min(tmp[flight[1]], dist[flight[0]] + flight[2]);
35                // cout << flight[1] << ": " << tmp[flight[1]] << endl;
36            }
37            swap(tmp, dist);
38        }
39        // cout << endl;
40        
41        return dist[dst] == MAX ? -1 : dist[dst];
42    }
43};
44
45//Single-Source Shortest Path:Dijkstra's Algorithm, priority queue
46//https://leetcode.com/problems/cheapest-flights-within-k-stops/discuss/115541/JavaPython-Priority-Queue-Solution
47//Runtime: 96 ms, faster than 45.17% of C++ online submissions for Cheapest Flights Within K Stops.
48//Memory Usage: 17.2 MB, less than 22.17% of C++ online submissions for Cheapest Flights Within K Stops.
49class Solution {
50public:
51    int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int K) {
52        vector<vector<pair<int, int>>> edges(n);
53        for(vector<int>& flight : flights){
54            //src -> (dst1, price1), (dst2, price2), ...
55            edges[flight[0]].emplace_back(flight[1], flight[2]);
56        }
57        
58        priority_queue<vector<int>, vector<vector<int>>, greater<vector<int>>> pq;
59        vector<int> cur;
60        int curCost, curSrc, curK;
61        
62        //(cost from source, current node, max distance to destination allowed)
63        pq.push({0, src, K+1});
64        
65        //visit nodes in increasing price order
66        while(!pq.empty()){
67            cur = pq.top(); pq.pop();
68            curCost = cur[0]; curSrc = cur[1]; curK = cur[2];
69            if(curSrc == dst){
70                return curCost;
71            }
72            if(curK > 0){
73                for(pair<int, int>& nei : edges[curSrc]){
74                    pq.push({curCost+nei.second, nei.first, curK-1});
75                }
76            }
77        }
78        
79        return -1;
80    }
81};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.