- 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
- 34 lines of Python from the credited upstream file minimum-cost-path-with-alternating-directions-iii.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.
123 45class Solution(object):6 def minCost(self, m, n, penalty):7 """8 :type m: int9 :type n: int10 :type penalty: List[List[int]]11 :rtype: int12 """13 DIRECTIONS = ((1, 1, 0), (1, 0, 1), (0, -1, 0), (0, 0, -1))14 dist = [[[float("inf")]*n for _ in xrange(m)] for _ in xrange(2)]15 np = ni = nj = 016 dist[np][ni][nj] = (ni+1)*(nj+1)17 min_heap = [(dist[np][ni][nj], np, ni, nj)]18 while min_heap:19 w, p, i, j = heapq.heappop(min_heap)20 if w != dist[p][i][j]:21 continue22 if (i, j) == (m-1, n-1):23 return w24 if w+penalty[i][j] < dist[p^1][i][j]:25 dist[p^1][i][j] = w+penalty[i][j]26 heapq.heappush(min_heap, (dist[p^1][i][j], p^1, i, j))27 for dp, di, dj in DIRECTIONS:28 np, ni, nj = p^1, i+di, j+dj29 if not (0 <= ni < m and 0 <= nj < n and w+(ni+1)*(nj+1)+(penalty[i][j] if np != dp else 0) < dist[np][ni][nj]):30 continue31 dist[np][ni][nj] = w+(ni+1)*(nj+1)+(penalty[i][j] if np != dp else 0)32 heapq.heappush(min_heap, (dist[np][ni][nj], np, ni, nj))33 return -134