Problem
There are n
cities connected by m
flights. Each flight starts from city u
and arrives at v
with a price w
.
Now given all the cities and flights, together with starting city src
and the destination dst
, your task is to find the cheapest price from src
to dst
with up to k
stops. If there is no such route, output -1
.
Example 1:
1 | Example 1: |
The graph looks like this:
Example 2:
1 | Example 2: |
The graph looks like this:
Constraints:
- The number of nodes
n
will be in range[1, 100]
, with nodes labeled from0
ton`` - 1
. - The size of
flights
will be in range[0, n * (n - 1) / 2]
. - The format of each flight will be
(src, ``dst``, price)
. - The price of each flight will be in the range
[1, 10000]
. k
is in the range of[0, n - 1]
.- There will not be any duplicated flights or self cycles.
Analysis
题目要求计算的是最短路径,限制条件是stop的次数。注意stop的次数和飞行的次数并不是相等的,为了和计算价钱同步,这里我用的是飞行的次数,也就是stop + 1
次。对于每一个city,记录从src
到该city的最小的cost。状态转移方程比较简单,使用上一次的city加上当次飞行的cost就是到该city的cost了。
Solution
使用二维数组记录dp状态,初始化的时候除了src
其余city都是不可达的,所以cost设置为一个很大的数字就可以了。
Code
1 | class Solution { |
Summary
这道题目主要的考点还是DP,比较难的是要想到从stop的次数开始遍历,后面状态转移方程相对来说比较简单。这道题目的分享到此为止,感谢您的支持,欢迎转发、评论,分享,谢谢!