You are given a 2D grid grid that represents a maze. Find the minimum number of moves needed to get from the start 'S' to the end 'E', or return -1 if 'E' cannot be reached. Each move steps to an adjacent cell: up, down, left or right.
Each cell holds one of these characters:
-
'.'
: open space, freely passable.
-
'#'
: wall, impassable.
-
'S'
: the start position.
-
'E'
: the end position.
-
'a'
to
'f'
: keys, which are picked up when you step on them.
-
'A'
to
'F'
: doors, which you can pass only after collecting the matching lowercase key (key
'a'
opens door
'A'
).
-
'0'
to
'9'
: teleporters, which come in pairs. Stepping onto a teleporter instantly transports you to the other teleporter with the same digit at no additional step cost.
Function Signature
def shortest_path(grid: list[list[str]]) -> int:
Rules
-
grid
is a list of rows, and each cell is a one-character string. Positions below are written as (row, col), counted from 0.
-
Every move costs 1. The jump itself costs nothing, so stepping onto a teleporter and landing on its twin counts as one move in total.
-
The teleport always happens. After stepping onto a teleporter you stand on its twin, and you cannot stop on the teleporter you stepped onto. Landing on a teleporter by teleport does not trigger it again; stepping off it and back on does.
-
A collected key stays collected and opens every door with its letter. Key cells and opened door cells stay passable.
-
A door whose key you do not hold blocks you like a wall.
-
'E'
always marks the end, so no door uses the letter
E
. A key
'e'
can be picked up but opens nothing.
-
'S'
is an ordinary open cell once you have left it.
Constraints
-
1 <= rows, cols <= 30
, where
rows = len(grid)
and
cols = len(grid[0])
-
Each cell is one of
'.'
,
'#'
,
'S'
,
'E'
,
'a'
-
'f'
,
'A'
-
'F'
,
'0'
-
'9'
-
There is exactly one
'S'
and exactly one
'E'
-
At most 6 distinct keys (
'a'
-
'f'
) appear in the grid
-
Each teleporter digit appears on exactly two cells or not at all
Examples
Input: grid = [["S",".",".","#","."],
[".","#","a","#","."],
[".","#","A",".","."],
[".",".",".","#","E"]]
Output: 7
Door 'A' at (2, 2) is the only way into the region that holds 'E', and key 'a' at (1, 2) can only be reached from (0, 2). The path goes right twice, down onto the key (3 moves), down through the door (4), right twice to (2, 4) (6) and down onto 'E' (7).
Input: grid = [["S",".","1","#","1",".","E"],
[".","#",".","#",".","#","."],
[".",".",".","#",".",".","."]]
Output: 4
Column 3 is all walls, so the teleporter is the only way across. Two moves reach the '1' at (0, 2), which sends you to (0, 4) at no extra cost, and two more moves to the right reach 'E'.
Input: grid = [["S","1","E"],
["#","#","#"],
["1",".","."]]
Output: 4
Stepping onto the '1' at (0, 1) sends you to (2, 0) (move 1), so you cannot walk straight along the top row. Step right to (2, 1) (move 2), step back onto the '1' at (2, 0) to land on (0, 1) (move 3), then step right onto 'E' (move 4).