There are n cities connected by m flights. Each fight starts from city and arrives at v with a price w.

Now given all the cities and fights, 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:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 1
Output: 200
Explanation:
The graph looks like this:

The cheapest price from city 0 to city 2 with at most 1 stop costs 200, as marked red in the picture.
Example 2:
Input:
n = 3, edges = [[0,1,100],[1,2,100],[0,2,500]]
src = 0, dst = 2, k = 0
Output: 500
Explanation:
The graph looks like this:

The cheapest price from city 0 to city 2 with at most 0 stop costs 500, as marked blue in the picture.

Note:

  • The number of nodes n will be in range [1, 100], with nodes labeled from 0 to n - 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.

这个题目有点类似于[Leetcode] 863. All Nodes Distance K in Binary Tree_ Medium tag: BFS, Amazon, 所以我用BFS, 只是不将dst add进入visited里面, 然后利用 stops <K来做一个

避免太多判断, 但是并不能pass所有的test cases, 我想可能是因为有些node需要重复利用, 因此就将visited去掉, 但是利用stops <K 和 psum <= ans 来避免过多的重复遍历某些不需要的值.

1. Constraints

1) 题目的Note解释很清楚, 基本没有特殊的test case, 但是没提到src == dst, 所以加上这个edge case

2. Ideas

BFS     时间复杂度还真的不好说...

3. Code

class Solution:
def cheapestFlight(self, n, flights, src, dst, K):
if src == dst: return 0
queue, graph, prices, ans = collections.deque([(src, -1, 0)]), collections.defaultdict(set), collections.Counter(), None
for s, e, p in flights:
graph[s].add(e)
prices[(s,e)] = p
while queue:
node, stops, psum = queue.popleft()
if stops <= K and (not ans or psum < ans):
if node == dst:
ans = psum
for each in graph[node]:
queue.append((each, stops + 1, psum + prices[(node, each)]))
return ans if ans else -1

[LeetCode] 787. Cheapest Flights Within K Stops_Medium tag: Dynamic Programming, BFS, Heap的更多相关文章

  1. LeetCode 787. Cheapest Flights Within K Stops

    原题链接在这里:https://leetcode.com/problems/cheapest-flights-within-k-stops/ 题目: There are n cities connec ...

  2. [LeetCode] 787. Cheapest Flights Within K Stops K次转机内的最便宜航班

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  3. 【LeetCode】787. Cheapest Flights Within K Stops 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:DFS 方法二:BFS 参考资料 日期 题目 ...

  4. 787. Cheapest Flights Within K Stops

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  5. [LeetCode] 139. Word Break_ Medium tag: Dynamic Programming

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine ...

  6. [LeetCode] 45. Jump Game II_ Hard tag: Dynamic Programming

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  7. [LeetCode] 63. Unique Paths II_ Medium tag: Dynamic Programming

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The ...

  8. [LeetCode] 121. Best Time to Buy and Sell Stock_Easy tag: Dynamic Programming

    Say you have an array for which the ith element is the price of a given stock on day i. If you were ...

  9. [LeetCode] 53. Maximum Subarray_Easy tag: Dynamic Programming

    Given an integer array nums, find the contiguous subarray (containing at least one number) which has ...

随机推荐

  1. PHP之Composer类库依赖管理神器

    Composer中文版说明见:https://github.com/kaka987/Composer-zh Composer 是PHP的类包依赖管理工具,用它可以轻松的引用第三方类包,类似于node的 ...

  2. 文件系统的挂载(2)---挂载rootfs文件系统

    一.目的 本文主要讲述linux内核rootfs文件系统的挂载过程,内核版本为3.10. rootfs是基于内存的文件系统,没有实际的存储设备,所有操作都在内存中完成.为了保证linux内核的精简性, ...

  3. 题目1005:Graduate Admission(录取算法)

    题目链接:http://ac.jobdu.com/problem.php?pid=1005 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...

  4. 题目1442:A sequence of numbers(数列计算以及二分求幂运用)

    题目链接:http://ac.jobdu.com/problem.php?pid=1442 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...

  5. Dumb Bones UVA - 10529[多米诺重构]

    Dumb Bones UVA - 10529   来自绿书p176  题意 你试图把一些多米诺骨牌排成直线,然后推倒它们.但是如果你在放骨牌的时候不小心把刚放的骨牌碰倒了,它就会把相临的一串骨牌全都碰 ...

  6. [工具] CuteMarkEd

    CuteMarkEd 是一款开源免费的.支持代码高亮的.朴素的 Markdown 本地编辑器,支持 Windows.Linux. 就因为程序员喜欢用,然后就拼命的开发 Markdown 编辑器么?青小 ...

  7. 7.18python进程池

    主要方法  常用的就是   from multiprocessing import Pool map() 同步 apply() 同步 apply_async()  异步  手动 close()  jo ...

  8. iOS 截屏分享(包含状态栏与不包含状态栏)

    iOS8以上的新方法PhotoKit 监听截图相册变化,取最后一张图片:http://www.hangge.com/blog/cache/detail_1515.html PhotoKit 获取本机相 ...

  9. php无限极分类递归与普通

    1. 递归 public function getInfo(){$data=$this->select();$arr=$this->noLimit($data,$f_id=0,$level ...

  10. Java实现验证码的产生和验证

    大家都知道为了防止我们的网站被有些人和黑客恶意攻击,比如我们网站的注册页面,如果我们在用户注册的时候不加上一个验证码框的话,别人就可以写一个脚本对你的网站进行恶意的注册,比如每分钟对你的网站进行n次的 ...