Problem Link

Description


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 ith row and jth 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 <= 103
  • 1 <= n == matrix[i].length <= 103
  • matrix[i][j] is either '#', '.', or an uppercase English letter.
  • matrix[0][0] is not an obstacle.

Solution


Python3

class Solution:
    def minMoves(self, matrix: List[str]) -> int:
        rows, cols = len(matrix), len(matrix[0])
        queue = deque([(0, 0, 0)])
        visited = [[False] * cols for _ in range(rows)]
        teleport = defaultdict(list)
 
        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] not in ".#":
                    teleport[matrix[i][j]].append((i, j))
 
        visited[0][0] = True
        res = 0
        teleported = [False] * 26
        
        while queue:
            x, y, cost = queue.popleft()
 
            if x == rows - 1 and y == cols - 1: 
                return cost
 
            if matrix[x][y] not in ".#" and not teleported[(k := ord(matrix[x][y]) - ord('A'))]:
                for dx, dy in teleport[matrix[x][y]]:
                    queue.appendleft((dx, dy, cost))
                    visited[dx][dy] = True
 
                teleported[k] = True
 
            for dx, dy in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
                if 0 <= dx < rows and 0 <= dy < cols and matrix[dx][dy] != '#' and not visited[dx][dy]:
                    queue.append((dx, dy, cost + 1))
                    visited[dx][dy] = True
 
        return -1