Grid Teleportation Traversal Problem
Description
LeetCode Problem 3552.
You are given a 2D character grid matrix of size m x n, represented as an array of strings, where matrix[i][j] represents the cell at the intersection of the i^th row and j^th column. Each cell is one of the following:
'.'representing an empty cell.'#'representing an obstacle.- An uppercase letter (
'A'-'Z') representing a teleportation portal.
You start at the top-left cell (0, 0), and your goal is to reach the bottom-right cell (m - 1, n - 1). You can move from the current cell to any adjacent cell (up, down, left, right) as long as the destination cell is within the grid bounds and is not an obstacle**.**
If you step on a cell containing a portal letter and you haven't used that portal letter before, you may instantly teleport to any other cell in the grid with the same letter. This teleportation does not count as a move, but each portal letter can be used at most once during your journey.
Return the minimum number of moves required to reach the bottom-right cell. If it is not possible to reach the destination, return -1.
Example 1:
Input: matrix = ["A..",".A.","..."]
Output: 2
Explanation:

- Before the first move, teleport from (0, 0) to (1, 1).
- In the first move, move from (1, 1) to (1, 2).
- In the second move, move from (1, 2) to (2, 2).
Example 2:
Input: matrix = [".#...",".#.#.",".#.#.","...#."]
Output: 13
Explanation:

Constraints:
1 <= m == matrix.length <= 10^31 <= n == matrix[i].length <= 10^3matrix[i][j]is either'#','.', or an uppercase English letter.matrix[0][0]is not an obstacle.
Solution
Approach: 0-1 BFS
Moving to a neighbouring cell costs 1 move, while stepping through a portal costs 0. That is a shortest path with weights 0 and 1, which a double-ended queue solves: weight-0 moves go to the front and weight-1 moves go to the back.
- Record the cells of each portal letter in a map.
- Keep a
distgrid, filled with infinity exceptdist[0][0] = 0. - When a cell is taken from the queue and it is a portal letter, push every other cell with that letter to the front with the same distance, then delete the letter from the map: using a portal twice can never help.
- Move to the four neighbours that are not obstacles and push them to the back with distance plus one whenever that improves
dist. - When the bottom-right cell is taken from the queue its distance is the answer. If the queue empties first, return
-1.
Complexity: O(m * n) time and O(m * n) extra space.
from collections import defaultdict, deque
from math import inf
class Solution:
def minMoves(self, matrix: List[str]) -> int:
m, n = len(matrix), len(matrix[0])
g = defaultdict(list)
for i, row in enumerate(matrix):
for j, c in enumerate(row):
if c.isalpha():
g[c].append((i, j))
dirs = (-1, 0, 1, 0, -1)
dist = [[inf] * n for _ in range(m)]
dist[0][0] = 0
q = deque([(0, 0)])
while q:
i, j = q.popleft()
d = dist[i][j]
if i == m - 1 and j == n - 1:
return d
c = matrix[i][j]
if c in g:
for x, y in g[c]:
if d < dist[x][y]:
dist[x][y] = d
q.appendleft((x, y))
del g[c]
for idx in range(4):
x, y = i + dirs[idx], j + dirs[idx + 1]
if (
0 <= x < m
and 0 <= y < n
and matrix[x][y] != "#"
and d + 1 < dist[x][y]
):
dist[x][y] = d + 1
q.append((x, y))
return -1