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. 【基础】java类的各种成员初始化顺序

    父子类继承时的静态代码块,普通代码块,静态方法,构造方法,等先后顺序 前言: 普通代码块:在方法或语句中出现的{}就称为普通代码块.普通代码块和一般的语句执行顺序由他们在代码中出现的次序决定--“先出 ...

  2. 【Spring源码深度解析学习系列】复杂标签属性解析(四)

    一.创建用于属性承载的BeanDefinition BeanDefiniton是一个接口,在Spring中存在三种实现:RootBeanDefinition.ChildBeanDefinition.G ...

  3. JS案例 - 可自动伸缩高度的textarea文本框

    文本框的默认现象: textarea如果设置cols和rows来规定textarea的尺寸,那么textarea的默认宽高是这俩属性设置的值,可以通过鼠标拖拽缩放文本框的尺寸. textarea如果设 ...

  4. 外网电脑配置8G运行内存,运行Android Studio,速度很轻松

    Win 7系统 之前RAM是 4 G,运行Android studio ,再运行浏览器或办公软件时卡的一比.再插入一个 4G内存条,总共8G时,速度嗖的一下就上来了.

  5. OGG日常运维监控的自动化脚本模板

    #!/usr/bin/ksh export ORACLE_BASE=/oracle/ export ORACLE_SID=epmln1 export ORACLE_HOSTNAME=pmlnpdb1 ...

  6. sql中的group by 和 having 用法解析

    转载博客:http://www.cnblogs.com/wang-123/archive/2012/01/05/2312676.html --sql中的group by 用法解析:-- Group B ...

  7. 调用TerminateProcess是无法触发DLL_PROCESS_DETACH的

    当应用程序中调用TerminateProcess函数,对于在DllMain函数中处理DLL_PROCESS_DETACH的额外代码操作是无法被执行的.比如:释放资源.数据持久化等.

  8. msyql DATETIME类型和Timestamp之间的转换

    DATETIME -> Timestamp: UNIX_TIMESTAMP(...) Timestamp -> DATETIME: FROM_UNIXTIME(...) select da ...

  9. ubuntu常用技巧积累

    1.修改root密码,一般与用户密码不同 python@ubuntu:~$ sudo passwd[sudo] password for python: 输入新的 UNIX 密码: 重新输入新的 UN ...

  10. NEFU 117 - 素数个数的位数 - [简单数学题]

    题目链接:http://acm.nefu.edu.cn/JudgeOnline/problemShow.php?problem_id=117 Time Limit:1000ms Memory Limi ...