- 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
- 59 lines of Python from the credited upstream file 3552.py.
- The implementation visibly relies on sequence storage, ordered lookup, 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 minMoves(self, matrix: list[str]) -> int:4 if matrix[-1][-1] == '#':5 return -16 7 teleportPositions = [[] for _ in range(26)]8 9 for i, row in enumerate(matrix):10 for j, c in enumerate(row):11 if c not in ('.', '#'):12 teleportPositions[ord(c) - ord('A')].append((i, j))13 14 return self._dijkstra(matrix, teleportPositions,15 (0, 0), (len(matrix) - 1, len(matrix[0]) - 1))16 17 def _dijkstra(18 self,19 matrix: list[str],20 teleportPositions: list[list[tuple[int, int]]],21 src: tuple[int, int],22 dst: tuple[int, int],23 ) -> int:24 DIRS = [(0, 1), (1, 0), (0, -1), (-1, 0)]25 m = len(matrix)26 n = len(matrix[0])27 dist = [[math.inf] * n for _ in range(m)]28 seen = set()29 30 dist[0][0] = 031 minHeap = [(dist[0][0], src)] 32 33 while minHeap:34 d, u = heapq.heappop(minHeap)35 if u == dst:36 return d37 i, j = u38 if d > dist[i][j]:39 continue40 c = matrix[i][j]41 if c.isupper() and c not in seen:42 seen.add(c)43 for x, y in teleportPositions[ord(c) - ord('A')]:44 if d < dist[x][y]:45 dist[x][y] = d46 heapq.heappush(minHeap, (d, (x, y)))47 for dx, dy in DIRS:48 x = i + dx49 y = j + dy50 if x < 0 or x == m or y < 0 or y == n:51 continue52 if matrix[x][y] == '#':53 continue54 if d + 1 < dist[x][y]:55 dist[x][y] = d + 156 heapq.heappush(minHeap, (d + 1, (x, y)))57 58 return -159