Locked Gates Grid: Fewest Steps With Collected Keys
Trees & GraphsAuto-graded · 20 test casesLast updated
Find the fewest moves through a grid where lowercase cells give keys and uppercase cells are gates, using BFS over position plus the set of collected keys.
You are given a rectangular grid of text rows. Starting from the cell marked S, find the fewest moves needed to stand on the cell marked T.
Cell meanings
Sis the starting cell. You begin there holding no keys.Tis the destination cell.#is a wall and can never be entered.- A lowercase letter is a key cell. Stepping onto it permanently adds that letter to your key set. Keys are not consumed.
- An uppercase letter is a gate. You may step onto it only if you already hold the matching lowercase key.
- Any other character (for example
.) is an open cell.
Important rule about S and T
Every uppercase letter is a gate, and this includes S and T. This has two consequences:
- You may step onto a
Tcell only if you already hold the keyt, which means you must have stepped onto a lowercasetcell earlier. - You may step back onto an
Scell after leaving it only if you hold the keys.
The start position itself needs no key. If the grid contains several S or several T characters, the last one in row-major order (top to bottom, left to right) is the real start or destination. All other copies behave as ordinary gates that need s or t respectively.
Movement
- One move goes to an adjacent cell: up, down, left, or right.
- You cannot leave the grid.
- Each move costs 1.
- The key check applies to the cell you are moving onto. A key you pick up counts immediately for the next move.
Task
Return the minimum number of moves needed to stand on T. Return -1 if it cannot be reached. Also return -1 if the grid is empty, its first row is empty, or it has no S or no T.
Constraints
mazeis a list of strings, all of equal length.- The grid is small enough for a search over (cell, key set) states.
- Letters are English letters; keys use lowercase
a-zand gates use uppercaseA-Z. - A gate whose key does not exist in the grid acts as a wall.
Examples
Example 1
Input: min_steps_with_keys(['S.aA.T'])
Output: -1
Example 2
Input: min_steps_with_keys(['S#.#T', '.a.b.', '#####'])
Output: -1
Example 3
Input: min_steps_with_keys(['S..a#', '##.A#', '...T#'])
Output: -1
Example 4
Input: min_steps_with_keys(['S..#B', 'a..#.', '...bT'])
Output: -1
Hints
Hint 1
Your position alone is not enough to describe where you are. Which cells you may enter depends on the keys you hold, so the state must include them.
Hint 2
Use BFS from the start, with each state being (row, column, set of keys). Mark a state visited when you enqueue it, and stop when you dequeue a state whose cell is the destination.
Hint 3
Test each neighbor in this order: bounds, wall, then any uppercase letter (including S and T) against the key set. Only after that do you add a lowercase letter to the key set.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a shortest-path problem where every move costs 1, so BFS is the right tool. Position alone is not a complete description of the situation. The same cell can be entered with different key sets, and the key set decides which neighbors are allowed. So the BFS state is (row, column, keys held).
- Scan the grid to find
SandT. If the grid is empty or either is missing, return-1. If a letter appears more than once, the last occurrence in scan order is kept. - Start BFS from
(start_row, start_col, empty key set)at distance 0. - When a state is dequeued, if its cell is the destination, return its distance. Because BFS dequeues states in non-decreasing distance order, this distance is minimal.
- For each of the four neighbors:
- Skip it if it is out of bounds or a wall.
- Skip it if it is an uppercase letter (including
SandT, which are gates in this problem) whose lowercase key is not held. - If it is a lowercase letter, add it to the key set for the new state.
- Skip the new state if it was already seen. Otherwise record it and enqueue it with distance + 1.
- If the queue empties, return
-1.
Why it is correct
Each state fully determines which moves are available, so the search is a plain BFS on a graph whose edges all have weight 1. A state reached a second time cannot have a shorter distance than the first arrival, so the visited set never discards a better path. Keys only accumulate, so the key set is monotone, and revisiting a cell is allowed only when the key set differs, which is exactly when it could help. Since T needs the key t, the destination is reachable only when a lowercase t cell is collected on the way.
Complexity
Let R x C be the grid size and K the number of distinct key letters present.
- Time: O(R * C * 2^K), since each state is expanded once with 4 neighbors.
- Space: O(R * C * 2^K) for the visited set and queue.
Reference solution
from collections import deque
from typing import List
def min_steps_with_keys(maze: List[str]) -> int:
if not maze or not maze[0]:
return -1
rows, cols = len(maze), len(maze[0])
start = target = None
for r in range(rows):
for c in range(cols):
if maze[r][c] == 'S':
start = (r, c)
elif maze[r][c] == 'T':
target = (r, c)
if start is None or target is None:
return -1
queue = deque([(start[0], start[1], frozenset(), 0)])
visited = {(start[0], start[1], frozenset())}
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
while queue:
r, c, keys, dist = queue.popleft()
if (r, c) == target:
return dist
for dr, dc in directions:
nr, nc = r + dr, c + dc
if nr < 0 or nr >= rows or nc < 0 or nc >= cols:
continue
cell = maze[nr][nc]
if cell == '#':
continue
if cell.isupper() and cell.lower() not in keys:
continue
new_keys = keys
if cell.islower():
new_keys = keys | {cell}
state = (nr, nc, new_keys)
if state in visited:
continue
visited.add(state)
queue.append((nr, nc, new_keys, dist + 1))
return -1