You are given a 2D grid grid of size m x n representing a maze. Each cell contains one of the following characters:
-
'.'
is an empty cell you can walk through.
-
'#'
is a wall that blocks movement.
-
'S'
is the start position.
-
'E'
is the exit position.
-
A lowercase letter (
'a'
to
'z'
) is a portal. Each letter that appears in the grid appears in exactly two cells, and those two cells form a portal pair.
Starting from S, in one step you may move to an adjacent cell (up, down, left, or right) that is not a wall. Additionally, if you step onto a portal cell, you may teleport to its matching portal cell (the other cell with the same letter) at a cost of 1 step. Using a portal is optional, and you may choose to walk through portal cells without teleporting.
Return the minimum number of steps required to reach E from S. If it is impossible to reach E, return -1.
Function Signature
def shortest_path_in_maze(grid: list[list[str]]) -> int:
Rules
-
grid
is a list of
m
rows, and each row is a list of
n
one-character strings.
-
Walking to an adjacent cell costs 1 step. Teleporting from a portal cell to the other cell of its pair also costs 1 step. Moves never leave the grid.
-
S
,
E
and portal cells are all walkable. A portal cell can be entered and left on foot like an empty cell.
-
Return only the step count, not the path.
Constraints
-
1 <= m, n <= 100
-
grid[i][j]
is one of
'.'
,
'#'
,
'S'
,
'E'
, or a lowercase letter
'a'
-
'z'
-
There is exactly one
'S'
and exactly one
'E'
in the grid
-
Each portal letter appears either
0
or
2
times in the grid
Examples
Input: grid = [
["S", ".", "#", ".", "E"],
[".", "#", "#", "#", "."],
[".", ".", ".", ".", "."]
]
Output: 8
There are no portals. The walls in the top two rows leave the bottom row as the only route between the left and right sides, so the shortest path goes down from S (2 steps), across the bottom row (4 steps) and up to E (2 steps).
Input: grid = [
["S", ".", "#", ".", "E"],
["a", "#", "#", "#", "a"],
[".", ".", "#", ".", "."]
]
Output: 3
Walk from S down to the left a (1 step), teleport to the right a (1 step), then walk up to E (1 step). Without the portal E is unreachable, because column 2 is a wall in every row.
Input: grid = [["S", "#", "E"]]
Output: -1
The only neighbor of S is a wall and there are no portals, so E cannot be reached.