Skip to content

Commit d3beb2a

Browse files
Alagappan MaruthappanAlagappan Maruthappan
Alagappan Maruthappan
authored and
Alagappan Maruthappan
committed
cheapest flight problem
1 parent 545d416 commit d3beb2a

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

cheapest_flight.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# https://leetcode.com/problems/cheapest-flights-within-k-stops/submissions/
2+
3+
import sys
4+
5+
6+
class Solution:
7+
def findCheapestPrice(self, n, flights, src, dst, K):
8+
"""
9+
:type n: int
10+
:type flights: List[List[int]]
11+
:type src: int
12+
:type dst: int
13+
:type K: int
14+
:rtype: int
15+
"""
16+
cities = [[] for _ in range(n)]
17+
for s, d, c in flights:
18+
cities[s].append((d, c))
19+
20+
distances_from_src = [sys.maxsize for _ in range(n)]
21+
distances_from_src[src] = 0
22+
for stop in range(K + 1):
23+
new_distances_from_src = distances_from_src[:]
24+
change = False
25+
for city in range(n):
26+
for a_city, a_city_cost in cities[city]:
27+
new_cost = a_city_cost + distances_from_src[city]
28+
if new_cost < new_distances_from_src[a_city]:
29+
new_distances_from_src[a_city] = new_cost
30+
change = True
31+
distances_from_src = new_distances_from_src
32+
if not change:
33+
break
34+
35+
cost = distances_from_src[dst]
36+
return cost if cost != sys.maxsize else -1
37+
38+
39+
assert Solution().findCheapestPrice(
40+
3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 1) == 200
41+
42+
assert Solution().findCheapestPrice(
43+
3, [[0, 1, 100], [1, 2, 100], [0, 2, 500]], 0, 2, 0) == 500

0 commit comments

Comments
 (0)