Collect Keys on a Grid with Locked Doors
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests grid-path DP where the traveler must collect keys to unlock doors, requiring bitmask state to track which keys have been picked up.
Collect Keys on a Grid with Locked Doors
You are given a rectangular grid of characters. A robot starts at the top-left cell (0, 0) and wants to reach the bottom-right cell (rows-1, cols-1).
Each cell contains one of the following characters:
| Character | Meaning |
|---|---|
'.' | Empty — always passable |
'#' | Wall — impassable |
'a'–'f' | Key — passable; picking it up adds it to the robot's key-ring |
'A'–'F' | Door — passable only if the robot already carries the matching lowercase key |
'S' | Start cell (0, 0) — treated as empty |
'E' | End cell (rows-1, cols-1) — treated as empty |
The robot may move up, down, left, or right one cell per step. It may revisit cells. When the robot enters a key cell it automatically picks up that key (a key already held is simply ignored). A door cell whose key is not held is impassable.
Your task: return the minimum number of steps to travel from S to E, or -1 if no such path exists.
Notes
- Keys used are only the lowercase letters
'a'through'f'(at most 6 distinct keys). - The grid contains at most 6 distinct key types (but may contain 0–6).
- The start and end cells may coincide (a 1×1 grid): return
0in that case. - The grid is guaranteed to have
'S'at(0, 0)and'E'at(rows-1, cols-1).
Constraints
1 ≤ rows, cols ≤ 201 ≤ rows × cols ≤ 400- Grid contains only
'.', '#', 'a'–'f', 'A'–'F', 'S', 'E' - At most 6 distinct lowercase key letters appear in the grid.
- The robot starts with no keys.
Examples
Example 1
Input: min_steps_collect_keys(['S', 'E'])
Output: -1
Example 2
Input: min_steps_collect_keys(['S.', 'aA', '.E'])
Output: -1
Example 3
Input: min_steps_collect_keys(['S#E'])
Output: -1
Hints
Hint 1
The state space is (row, col, key_bitmask). Encode which keys the robot holds as a bitmask of up to 6 bits — this keeps the total number of states at most 20 × 20 × 64 = 25,600, which is tiny.
Hint 2
Use BFS (not DP with relaxation) because every step costs 1; BFS guarantees the first time a state is reached it is reached in the minimum number of steps.
Hint 3
When you step onto a key cell, compute the new bitmask by OR-ing the current mask with that key's bit. When you try to step onto a door cell, check whether the corresponding key bit is set in the current mask before allowing the move.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight: State = Position + Key Bitmask
Moving on a grid alone is plain BFS. The twist here is that the robot's ability to pass through a door depends on which keys it holds — so the "same cell" visited with different key sets is a different state. We encode the key-ring as a bitmask of at most 6 bits (one per letter a–f), giving at most 2^6 = 64 possible key states. Combined with at most 20×20 = 400 cells, the total state space is at most 25,600 states — tiny.
Algorithm: BFS over (row, col, keys)
BFS is the right tool because every step costs exactly 1. The first time BFS reaches a state it does so in the minimum number of steps, so no relaxation or priority queue is needed.
Transitions: from state (r, c, keys) try all four neighbors (nr, nc):
- Skip walls (
#). - Skip door cells
Xifkeysdoes not contain the bit for the lowercase version ofX. - If the cell is a key
x, setnew_keys = keys | bit(x); otherwisenew_keys = keys. - If
(nr, nc, new_keys)has not been visited, enqueue it. - If
(nr, nc)is the goal, returnsteps + 1immediately.
If the queue empties without reaching the goal, return -1.
Correctness
- Picking up a key never hurts, so we always update the bitmask immediately.
- The visited set prevents cycling: a state
(r, c, keys)is only processed once, and since keys can only increase, we never re-process a state with a strictly larger key set from a shorter path (BFS already guarantees that).
Complexity
- Time: O(rows × cols × 2^K) where K ≤ 6, so O(400 × 64) = O(25,600) states, each processed once with 4 neighbors → O(102,400) — effectively constant for the given constraints.
- Space: O(rows × cols × 2^K) for the visited set and queue.
from typing import List
from collections import deque
def min_steps_collect_keys(grid: List[str]) -> int:
rows = len(grid)
cols = len(grid[0])
if rows == 1 and cols == 1:
return 0
start_keys = 0
cell = grid[0][0]
if 'a' <= cell <= 'f':
start_keys |= (1 << (ord(cell) - ord('a')))
queue = deque()
queue.append((0, 0, start_keys, 0))
visited = set()
visited.add((0, 0, start_keys))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while queue:
r, c, keys, steps = queue.popleft()
for dr, dc in directions:
nr, nc = r + dr, c + dc
if not (0 <= nr < rows and 0 <= nc < cols):
continue
ch = grid[nr][nc]
if ch == '#':
continue
if 'A' <= ch <= 'F':
bit = 1 << (ord(ch) - ord('A'))
if not (keys & bit):
continue
new_keys = keys
if 'a' <= ch <= 'f':
new_keys |= (1 << (ord(ch) - ord('a')))
if nr == rows - 1 and nc == cols - 1:
return steps + 1
state = (nr, nc, new_keys)
if state not in visited:
visited.add(state)
queue.append((nr, nc, new_keys, steps + 1))
return -1