Graph Theory37 sections · 1633 units
Open in Course

LeetCode 787 Cheapest Flights Within K Stops - Implementation

Code solution

Here is the solution:

function findCheapestPrice(n, flights, src, dst, k):
    adj = array of n empty lists
    for (u, v, price) in flights:
        adj[u].append((v, price))

    pq = min-heap with (0, src, k + 1)

    while pq is not empty:
        (cost, city, stops) = pq.pop()
        if city == dst:
            return cost
        if stops > 0:
            for (next, price) in adj[city]:
                pq.push((cost + price, next, stops - 1))

    return -1

This runs in O(Eklog(Ek))O(E \cdot k \log (E \cdot k)) time and uses O(Ek)O(E \cdot k) space.