You are planning a trip between two cities and want to find the cheapest route. You are given a list of direct flights flights, where each flight flights[i] = [from_i, to_i, price_i] is a one-way flight from city from_i to city to_i that costs price_i.
Cities are integers in the range [0, n - 1], where n is the total number of cities. Given a starting city src and a destination city dst, return the minimum total cost to travel from src to dst. If there is no valid route from src to dst, return -1.
Function Signature
def plan_itinerary(n: int, flights: list[list[int]], src: int, dst: int) -> int:
Rules
-
A flight
[a, b, p]
goes from
a
to
b
only. It cannot be used to fly from
b
to
a
.
-
A route may use any number of flights. Its cost is the sum of the prices of the flights on it.
-
Return only the minimum cost, not the route. If
dst
cannot be reached from
src
, return
-1
.
Constraints
-
1 <= n <= 100
-
0 <= len(flights) <= n * (n - 1)
-
len(flights[i]) == 3
-
0 <= from_i, to_i < n
and
from_i != to_i
-
1 <= price_i <= 10^4
-
0 <= src, dst < n
and
src != dst
Examples
Input: n = 4, flights = [[0,1,100],[1,2,100],[0,2,500],[2,3,100]], src = 0, dst = 3
Output: 300
The route 0 -> 1 -> 2 -> 3 costs 100 + 100 + 100 = 300. The only other route, 0 -> 2 -> 3, costs 500 + 100 = 600.
Input: n = 3, flights = [[0,1,100],[1,2,100],[0,2,500]], src = 0, dst = 2
Output: 200
Two routes exist: 0 -> 1 -> 2 costs 200 and the direct flight 0 -> 2 costs 500. The cheaper route wins even though it uses more flights.
Input: n = 3, flights = [[0,1,100],[2,1,50]], src = 0, dst = 2
Output: -1
From city 0 you can only reach city 1, and city 1 has no outgoing flights. The flight [2,1,50] goes from 2 to 1, so it cannot be used to reach city 2.