Minimum Steps to Collect All Keys in a Grid Maze
Trees & GraphsAuto-graded · 17 test casesLast updated
Tests BFS shortest path on a grid where state must encode both position and the set of collected keys, requiring multi-dimensional state space exploration.
Minimum Steps to Collect All Keys in a Grid Maze
You are given a rectangular grid maze represented as a list of strings. Each cell is one of the following characters:
| Character | Meaning |
|---|---|
'.' | Open passage |
'#' | Wall (impassable) |
'@' | Starting position |
'a'–'f' | A key (lowercase letter) — walking onto it collects it |
'A'–'F' | A locked door (uppercase letter) — passable only if you already hold the matching key ('a' for 'A', etc.) |
Your task is to find the minimum number of steps needed to collect every key present in the grid, starting from '@'. You may move one step at a time — up, down, left, or right. You cannot step outside the grid boundaries.
Return the minimum number of steps, or -1 if it is impossible to collect all keys.
Notes
- There is always exactly one starting position
'@'. - Keys are the lowercase letters actually present in the grid; there may be 0 to 6 of them (
'a'through'f'). - Doors whose matching key is not present in the grid are treated as open passages (you will never need the missing key, so they do not block you).
- You do not need to return to the starting position.
- Once all keys are collected you stop immediately (you do not have to walk through every door).
Constraints
1 ≤ len(grid) ≤ 30(number of rows)1 ≤ len(grid[0]) ≤ 30(number of columns)- All rows have the same length.
- The grid contains exactly one
'@'. - The grid contains at most 6 distinct keys (
'a'–'f'). - Characters are only those listed in the table above.
Examples
Example 1
Input: min_steps_collect_keys(['@.a.#', '###.#', 'b.A.B'])
Output: 8
Example 2
Input: min_steps_collect_keys(['@..aA', '......', '......', 'b#####', '....B.'])
Output: 9
Example 3
Input: min_steps_collect_keys(['@'])
Output: 0
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight: State = Position + Key Bitmask
Standard BFS on a grid tracks state as (row, col). Here, the same cell can be visited multiple times with different subsets of keys in hand — each combination is meaningfully different. So the full BFS state is (row, col, keys_held) where keys_held is a bitmask over at most 6 keys (bits 0–5 for keys 'a'–'f').
Algorithm
- Pre-scan the grid to find
@(start) and buildall_keys, a bitmask of every key that actually exists. - Edge case: if
all_keys == 0, return0immediately. - BFS from
(start_r, start_c, 0)withsteps = 0.- Each neighbour cell is evaluated:
- Skip walls (
#). - Skip locked doors whose matching key exists in the grid and is not yet held.
- If the cell holds a key, set its bit in
new_keys. - If
new_keys == all_keys, returnsteps + 1. - Otherwise enqueue
(nr, nc, new_keys, steps+1)if not yet visited for this exact(nr, nc, new_keys)triple.
- Skip walls (
- Each neighbour cell is evaluated:
- If the queue empties, return
-1.
Why This is Correct
BFS guarantees the first time any state is dequeued it was reached in the minimum number of steps. Because we only visit each (r, c, mask) triple once, we never revisit a state. The state space is at most 30 × 30 × 2^6 = 57,600 nodes, so BFS is extremely fast even on maximum-sized grids.
Door Rule Detail
A door 'X' is only blocking if the corresponding key 'x' is actually present in the grid. If the key is absent, the door is treated as open passage — this prevents impossible scenarios due to unreachable/non-existent keys.
Complexity
- Time: O(R × C × 2^K) where K ≤ 6, R ≤ 30, C ≤ 30 → at most ~57,600 states, each with 4 neighbours → O(230,400) operations.
- Space: O(R × C × 2^K) for the visited array and queue.
Reference Solution
from typing import List
from collections import deque
def min_steps_collect_keys(grid: List[str]) -> int:
rows = len(grid)
cols = len(grid[0])
start_r = start_c = 0
all_keys = 0
key_in_grid = set()
for r in range(rows):
for c in range(cols):
ch = grid[r][c]
if ch == '@':
start_r, start_c = r, c
elif 'a' <= ch <= 'f':
key_in_grid.add(ch)
all_keys |= 1 << (ord(ch) - ord('a'))
if all_keys == 0:
return 0
visited = [[[False] * (1 << 6) for _ in range(cols)] for _ in range(rows)]
queue = deque()
init_mask = 0
queue.append((start_r, start_c, init_mask, 0))
visited[start_r][start_c][init_mask] = True
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while queue:
r, c, keys_held, 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':
door_bit = 1 << (ord(ch) - ord('A'))
if ch.lower() in key_in_grid and not (keys_held & door_bit):
continue
new_keys = keys_held
if 'a' <= ch <= 'f':
new_keys |= 1 << (ord(ch) - ord('a'))
if new_keys == all_keys:
return steps + 1
if visited[nr][nc][new_keys]:
continue
visited[nr][nc][new_keys] = True
queue.append((nr, nc, new_keys, steps + 1))
return -1