|
| 1 | +import heapq |
| 2 | +import collections |
| 3 | + |
| 4 | +""" |
| 5 | +We start from src and only got K+1 stops to use |
| 6 | +Each time, we choose the cheapest place to go. |
| 7 | +
|
| 8 | +If the city we popout is dst, then the price must be lowest |
| 9 | +Since we always pick the lowest place to go. |
| 10 | +
|
| 11 | +If we still have stops left (stops>1), we put its neighbor to the priority queue. |
| 12 | +So the city in the priority queue must be within the stops limit. |
| 13 | +
|
| 14 | +Making the graph takes O(E) |
| 15 | +The size of priority queue is O(V), since we might put all the cities in it. |
| 16 | +So for every pop, it is O(LogV). Total is O(VLogV). |
| 17 | +For every edge we call an heappush, so that is ELogV |
| 18 | +O(E+ (V+E)LogV) -> O((V+E)LogV) |
| 19 | +V is the number of cities within range K stops. |
| 20 | +""" |
| 21 | +#Dijkstra |
| 22 | +class Solution1(object): |
| 23 | + def findCheapestPrice(self, n, flights, src, dst, K): |
| 24 | + graph = collections.defaultdict(list) |
| 25 | + pq = [] |
| 26 | + |
| 27 | + for u, v, w in flights: graph[u].append((w, v)) |
| 28 | + |
| 29 | + heapq.heappush(pq, (0, K+1, src)) |
| 30 | + while pq: |
| 31 | + price, stops, city = heapq.heappop(pq) |
| 32 | + |
| 33 | + if city is dst: return price |
| 34 | + if stops>0: |
| 35 | + for price_to_nei, nei in graph[city]: |
| 36 | + heapq.heappush(pq, (price+price_to_nei, stops-1, nei)) |
| 37 | + return -1 |
| 38 | + |
| 39 | +""" |
| 40 | +This is mostly straight forward BFS. |
| 41 | +When we are out of stops, or price is greater than min_price, we stop adding cities to the queue. |
| 42 | +Every time we encounter dst we compare the price and set it to the min. |
| 43 | +
|
| 44 | +Making the graph takes O(E) |
| 45 | +BFS every node in adjacent list takes O(V+E) |
| 46 | +V is the number of cities within range K stops. |
| 47 | +""" |
| 48 | +#BFS |
| 49 | +class Solution2(object): |
| 50 | + def findCheapestPrice(self, n, flights, src, dst, K): |
| 51 | + graph = collections.defaultdict(list) |
| 52 | + q = collections.deque() |
| 53 | + min_price = float('inf') |
| 54 | + |
| 55 | + for u, v, w in flights: graph[u].append((w, v)) |
| 56 | + q.append((src, 0, 0)) |
| 57 | + while q: |
| 58 | + city, stops, price = q.popleft() |
| 59 | + if city==dst: |
| 60 | + min_price = min(min_price, price) |
| 61 | + continue |
| 62 | + |
| 63 | + if stops<=K and price<=min_price: |
| 64 | + for price_to_nei, nei in graph[city]: |
| 65 | + q.append((nei, stops+1, price+price_to_nei)) |
| 66 | + |
| 67 | + return min_price if min_price!=float('inf') else -1 |
| 68 | + |
0 commit comments