Skip to content

Instantly share code, notes, and snippets.

@willwangcc
Last active April 16, 2018 18:43
Show Gist options
  • Save willwangcc/4efb3251c02c1d39775cf7eed580b154 to your computer and use it in GitHub Desktop.
Save willwangcc/4efb3251c02c1d39775cf7eed580b154 to your computer and use it in GitHub Desktop.
# Time: O(E∗K), where E is the length of flights.
# Space: O(n), the space used to store cur and pre
# Reference: https://leetcode.com/problems/cheapest-flights-within-k-stops/solution/
# Bellman-ford algorithm
class Solution(object):
def findCheapestPrice(self, n, flights, src, dst, K):
"""
:type n: int
:type flights: List[List[int]]
:type src: int
:type dst: int
:type K: int
:rtype: int
"""
dist = [[float('inf')] * n for _ in xrange(2)] # [pre, cur] or [cur, pre]
dist[0][src] = dist[1][src] = 0
for i in xrange(K+1):
for u, v, w in flights:
dist[i&1][v] = min(dist[i&1][v], dist[~i&1][u] + w)
return dist[K&1][dst] if dist[K&1][dst] < float('inf') else -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment