Cheapest Flights Within K Stops
LeetCode 787 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Heap on (cost, node, stops); skip when stops > k or stops ≥ fewest stops already seen at that node.
ನಾನು Cheapest Flights Within K Stops (LeetCode 787) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Shortest Path / BFS-Dijkstra ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Plain Dijkstra finds the cheapest route but ignores how many stops it uses. Put the stop count into the heap entries and prune: a node is worth expanding again only if we reach it with fewer stops than before, because a cheaper-but-longer path seen earlier may run out of stops.
Approach
- 1
Build an adjacency list from the flights.
- 2
Push (0, src, 0) onto a min-heap.
- 3
Pop the cheapest; if it's dst, that cost is the answer.
- 4
Skip entries that used too many stops or more stops than an earlier visit.
- 5
Otherwise record the stops and push every neighbour with cost + price and stops + 1.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Dijkstra with stop pruningPythonO(E·k log) time
class Solution:
def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int:
#we need to minimize cost
min_heap =[(0,src,0)]#cost,node,stops
adj = defaultdict(list)
for u,v,w in flights:
adj[u].append((v,w))
stops = [float("inf")]*n
stops[src]=0
while min_heap:
cost,node,steps=heapq.heappop(min_heap)
if node==dst:
return cost
#if we can't reach in k stops or earlier we found a better path with less no of stops
#we can skip
if steps>k or steps>stops[node]:
continue
stops[node]=steps
for adj_node,wt in adj[node]:
heapq.heappush(min_heap,(cost+wt,adj_node,steps+1))
return -1Cheapest Flights Within K Stops — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Cheapest Flights Within K Stops ಹಿಂದಿನ intuition ಏನು?
Plain Dijkstra finds the cheapest route but ignores how many stops it uses. Put the stop count into the heap entries and prune: a node is worth expanding again only if we reach it with fewer stops than before, because a cheaper-but-longer path seen earlier may run out of stops.
Cheapest Flights Within K Stops (LeetCode 787) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Build an adjacency list from the flights. 2. Push (0, src, 0) onto a min-heap. 3. Pop the cheapest; if it's dst, that cost is the answer. 4. Skip entries that used too many stops or more stops than an earlier visit. 5. Otherwise record the stops and push every neighbour with cost + price and stops + 1.
Cheapest Flights Within K Stops ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(E · k · log(E · k)). Space: O(E · k). (Accepted approach: Dijkstra with stop pruning.)
Cheapest Flights Within K Stops ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Standard 'visited' marking breaks this problem — a pricier path with fewer stops may be the only valid one. k stops means k + 1 flights.