Faaez Razeen

Cheapest Flights Within K Stops

  • 3 min read
  • Graph
  • LC-Medium

3 years ago

Solution

TimeSpaceExplanation
O(E * k)O(E)Algorithm runs k times for each edge
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: prices = [math.inf] * n prices[src] = 0 for _ in range(k + 1): temp_prices = prices[:] for s, d, p in flights: if prices[s] == math.inf: continue if prices[s] + p < temp_prices[d]: temp_prices[d] = prices[s] + p prices = temp_prices return -1 if prices[dst] == math.inf else prices[dst]