Cheapest Flights Within K Stops

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, a…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by SalahElhossiny

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.


class Solution:
    def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
        prices = [float("inf")] * n
        prices[src] = 0

        for i in range(k + 1):
            tmpPrices = prices.copy()

            for s, d, p in flights:  # s=source, d=dest, p=price
                if prices[s] == float("inf"):
                    continue
                if prices[s] + p < tmpPrices[d]:
                    tmpPrices[d] = prices[s] + p
            prices = tmpPrices

        return -1 if prices[dst] == float("inf") else prices[dst]


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by SalahElhossiny


Print Share Comment Cite Upload Translate Updates
APA

SalahElhossiny | Sciencx (2022-09-10T06:20:33+00:00) Cheapest Flights Within K Stops. Retrieved from https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/

MLA
" » Cheapest Flights Within K Stops." SalahElhossiny | Sciencx - Saturday September 10, 2022, https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/
HARVARD
SalahElhossiny | Sciencx Saturday September 10, 2022 » Cheapest Flights Within K Stops., viewed ,<https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/>
VANCOUVER
SalahElhossiny | Sciencx - » Cheapest Flights Within K Stops. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/
CHICAGO
" » Cheapest Flights Within K Stops." SalahElhossiny | Sciencx - Accessed . https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/
IEEE
" » Cheapest Flights Within K Stops." SalahElhossiny | Sciencx [Online]. Available: https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/. [Accessed: ]
rf:citation
» Cheapest Flights Within K Stops | SalahElhossiny | Sciencx | https://www.scien.cx/2022/09/10/cheapest-flights-within-k-stops/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.