Shortest Path Through a Grid With Keys and One-Way Portals
Trees & GraphsAuto-graded · 21 test casesLast updated
Tests BFS/Dijkstra on an augmented state space where position must be combined with a key-collection bitmask, and directional arrow tiles enforce constrained traversal.
Background
You are navigating an N × M grid from the top-left corner (0, 0) toward a single goal cell. The grid is filled with different types of tiles, and some tiles impose movement restrictions or bonuses.
Tile Types
| Symbol | Meaning |
|---|---|
. | Open floor — you may pass through freely. |
# | Wall — impassable. |
K | Key — picking it up adds it to your inventory. |
T | Exit — you may only finish here once every key on the entire grid is in your inventory. Until then, T acts like a wall. |
^ v < > | Arrow tile — see rules below. |
Arrow Rules
An arrow tile points in one of the four cardinal directions. Two rules govern them:
- Entry constraint. You may only step onto an arrow tile if you are already moving in the direction the arrow points. Trying to enter it from any other direction is forbidden.
- Forced continuation. The moment you land on an arrow tile, you are immediately pushed one additional cell in the same direction. That extra cell costs 1 step just like any other move.
- If the forced destination is out of bounds, a wall, or an arrow that you cannot legally enter (wrong direction), the entire move is invalid.
- If the forced destination is another valid same-direction arrow, the push repeats from that cell, consuming 1 step per cell.
Task
Implement a function that receives the grid and returns the minimum total number of cells entered on any valid path from (0, 0) to T while collecting all keys. Return -1 if no such path exists.
Every cell you move into (including cells entered through arrow-forced slides) counts as one step.
Constraints
1 <= N, M <= 50- The number of
Ktiles in the grid is at most 5. - The starting cell
(0, 0)is never a wall. - There is at most one
Ttile. - Arrow tiles only point in the four cardinal directions (
^,v,<,>).
Notes
- If
(0, 0)contains a key, it is collected before any move is made. - If
(0, 0)is alreadyTand there are no keys anywhere, return0. - Keys already collected are not collected a second time.
Examples
Example 1
Input: shortest_key_path([['.', 'K', '#'], ['^', '.', '.'], ['T', '.', '.']])
Output: 4
Hints
Hint 1
Position alone is not enough to define a state — two visits to the same cell with different keys collected are independent states that must both be explored.
Hint 2
Model this as a weighted shortest-path problem: a move that triggers a chain of k arrow slides costs k steps total, so edge weights are not uniform and a priority queue beats plain BFS.
Hint 3
Precompute a bit-index for every key cell so that your inventory can be represented as a single integer bitmask; the goal condition is simply mask == (1 << total_keys) - 1.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why position alone is not enough
Two visits to the same cell are meaningfully different if you hold different keys on each visit. A path that arrives at cell X with fewer keys may later reach the exit while a path that arrives with more keys may reach it sooner. To avoid discarding valid paths, the full state must be (row, col, key_mask) where key_mask is a bitmask recording which keys have been collected.
With at most 5 keys the mask fits in a 5-bit integer (32 possible values), so the total state space is at most 50 × 50 × 32 = 80,000 states — completely tractable.
Why Dijkstra rather than plain BFS
Each player action costs exactly 1 step, but a single action can slide you through a chain of arrow tiles, spending 1 step per cell entered. Two different valid moves from the same state can therefore have different costs (1 step vs. 2, 3, … steps). Edge weights are non-uniform, so BFS would not guarantee the shortest path. Dijkstra with a min-heap correctly expands states in non-decreasing cost order.
Encoding keys as a bitmask
During a preprocessing pass, every K cell is assigned a unique index 0–4. Holding key i means bit i is set in mask. Collecting a key is mask |= (1 << i). The exit is unlocked when mask == (1 << total_keys) - 1.
Simulating arrow chains
When trying to move in direction d from (r, c):
- Step to the immediate neighbor
(nr, nc), counting 1 step. - Check validity: in-bounds, not a wall, not
Twith an incomplete mask, not an arrow pointing in a direction other thand. - Collect a key if present.
- If the cell is itself an arrow pointing in direction
d, advance one more cell and count another step — repeat from step 2. - If the cell is not an arrow, the move ends here.
This loop naturally handles chains of arbitrary length and rejects incompatible arrows.
Correctness
- Dijkstra's algorithm is optimal for graphs with non-negative edge weights, which holds here (every step costs ≥ 1).
- The visited check (
distance != distances.get(state)) is the standard lazy-deletion pattern: stale heap entries are skipped, so each state is processed at most once. - Masks never lose bits (keys are never dropped), so returning to a previously visited
(r, c, mask)state via a longer path can never improve anything — the visited set is sound. - The exit is only recognised as terminal when
mask == full_mask, enforcing the all-keys requirement.
Edge cases
- Key at the start: initialise
start_maskbefore queuing the first state. - Exit at the start with no keys: return 0 immediately.
- Forced slide into a wall or off the grid: the
valid = Falsebranch discards that transition entirely. - No exit tile, or exit completely walled off: the heap empties and the function returns
-1.
Complexity
- States: O(N · M · 2^K)
- Edges per state: 4 directions, each slide at most O(N + M) cells long
- Time: O(N · M · 2^K · (N + M) · log(N · M · 2^K))
- Space: O(N · M · 2^K)
With N = M = 50 and K = 5 this is around 80,000 states — negligible in practice.
Reference solution
from heapq import heappop, heappush
from typing import List
def shortest_key_path(grid: List[List[str]]) -> int:
n, m = len(grid), len(grid[0])
key_ids = {}
target = None
for r in range(n):
for c in range(m):
tile = grid[r][c]
if tile == 'K':
key_ids[(r, c)] = len(key_ids)
elif tile == 'T':
target = (r, c)
full_mask = (1 << len(key_ids)) - 1
start_mask = 0
if (0, 0) in key_ids:
start_mask = 1 << key_ids[(0, 0)]
if target == (0, 0) and start_mask == full_mask:
return 0
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
arrow_direction = {'^': 0, 'v': 1, '<': 2, '>': 3}
start = (0, 0, start_mask)
distances = {start: 0}
heap = [(0, 0, 0, start_mask)]
while heap:
distance, r, c, mask = heappop(heap)
state = (r, c, mask)
if distance != distances.get(state):
continue
if (r, c) == target and mask == full_mask:
return distance
for direction, (dr, dc) in enumerate(directions):
nr, nc = r + dr, c + dc
next_mask = mask
steps = 1
valid = True
while True:
if not (0 <= nr < n and 0 <= nc < m):
valid = False
break
tile = grid[nr][nc]
if tile == '#':
valid = False
break
if tile == 'T' and next_mask != full_mask:
valid = False
break
if tile in arrow_direction and arrow_direction[tile] != direction:
valid = False
break
if (nr, nc) in key_ids:
next_mask |= 1 << key_ids[(nr, nc)]
if tile not in arrow_direction:
break
nr += dr
nc += dc
steps += 1
if not valid:
continue
next_state = (nr, nc, next_mask)
new_distance = distance + steps
if new_distance < distances.get(next_state, float('inf')):
distances[next_state] = new_distance
heappush(heap, (new_distance, nr, nc, next_mask))
return -1