- 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
- 51 lines of Python from the credited upstream file 2662.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 def minimumCost(3 self,4 start: list[int],5 target: list[int],6 specialRoads: list[list[int]],7 ) -> int:8 return self.dijkstra(specialRoads, *start, *target)9 10 def dijkstra(11 self,12 specialRoads: list[list[int]],13 srcX: int,14 srcY: int,15 dstX: int,16 dstY: int,17 ) -> int:18 n = len(specialRoads)19 20 dist = [math.inf] * n21 minHeap = [] 22 23 24 for u, (x1, y1, _, _, cost) in enumerate(specialRoads):25 d = abs(x1 - srcX) + abs(y1 - srcY) + cost26 dist[u] = d27 heapq.heappush(minHeap, (dist[u], u))28 29 while minHeap:30 d, u = heapq.heappop(minHeap)31 if d > dist[u]:32 continue33 _, _, ux2, uy2, _ = specialRoads[u]34 for v in range(n):35 if v == u:36 continue37 vx1, vy1, _, _, vcost = specialRoads[v]38 39 newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost40 if newDist < dist[v]:41 dist[v] = newDist42 heapq.heappush(minHeap, (dist[v], v))43 44 ans = abs(dstX - srcX) + abs(dstY - srcY)45 for u in range(n):46 _, _, x2, y2, _ = specialRoads[u]47 48 ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2))49 50 return ans51