- Define the priority key and whether the smallest or largest item should lead.
- Push each candidate when it becomes eligible.
- Discard stale entries when necessary and process the best live candidate.
Code notes
- 46 lines of Python from the credited upstream file 2714.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 3 def shortestPathWithHops(4 self,5 n: int,6 edges: list[list[int]],7 s: int,8 d: int,9 k: int,10 ) -> int:11 graph = [[] for _ in range(n)]12 13 for u, v, w in edges:14 graph[u].append((v, w))15 graph[v].append((u, w))16 17 return self._dijkstra(graph, s, d, k)18 19 def _dijkstra(20 self,21 graph: list[list[tuple[int, int]]],22 src: int,23 dst: int,24 k: int,25 ) -> int:26 dist = [[math.inf for _ in range(k + 1)] for _ in range(len(graph))]27 28 dist[src][k] = 029 minHeap = [(dist[src][k], src, k)] 30 31 while minHeap:32 d, u, hops = heapq.heappop(minHeap)33 if u == dst:34 return d35 if dist[u][hops] > d:36 continue37 for v, w in graph[u]:38 39 if d + w < dist[v][hops]:40 dist[v][hops] = d + w41 heapq.heappush(minHeap, (dist[v][hops], v, hops))42 43 if hops > 0 and d < dist[v][hops - 1]:44 dist[v][hops - 1] = d45 heapq.heappush(minHeap, (dist[v][hops - 1], v, hops - 1))46