Shortest Path To Get All Keys Problem
Description
LeetCode Problem 864.
You are given an m x n grid grid where:
- '.' is an empty cell.
- '#' is a wall.
- '@' is the starting point.
- Lowercase letters represent keys.
- Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.
If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.
For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.
Return the lowest number of moves to acquire all keys. If it is impossible, return -1.
Example 1:
Input: grid = ["@.a.#","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.
Example 2:
Input: grid = ["@..aA","..B#.","....b"]
Output: 6
Example 3:
Input: grid = ["@Aa"]
Output: -1
Constraints:
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 30
- grid[i][j] is either an English letter, '.', '#', or '@'.
- The number of keys in the grid is in the range [1, 6].
- Each key in the grid is unique.
- Each key in the grid has a matching lock.
Solution
Approach: Breadth-First Search over (Cell, Keys Held)
A plain BFS over cells does not work: the shortest route may pass through the same cell twice, once before picking up a key and once after (to go back and open a lock). What matters is not only where you stand but also which keys you hold. So the BFS state is (row, col, keys), where keys is a bitmask of collected keys (bit i set means key 'a' + i is held). There are at most 30 · 30 · 26 = 57,600 states.
- Find the start
@and count the keysk. The goal mask is(1 << k) - 1, because the keys are exactly the firstkletters. - BFS level by level from
(startRow, startCol, 0), counting the levels as moves. - From each state try the four neighbors. Skip walls, cells outside the grid, and locks whose bit is not in
keys. Stepping onto a key sets its bit. - The first state whose mask equals the goal gives the answer; if the queue empties first, return
-1.
The detail that matters is marking visited per state, not per cell: the same cell with a different set of keys is a new state and must be explored again.
Complexity: O(m · n · 2k) time and space, where m × n is the grid size and k (at most 6) is the number of keys.
import collections
class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
rows, cols = len(grid), len(grid[0])
key_count = 0
start_row = start_col = 0
for r in range(rows):
for c in range(cols):
cell = grid[r][c]
if cell == "@":
start_row, start_col = r, c
elif "a" <= cell <= "z":
key_count += 1
all_keys = (1 << key_count) - 1 # the keys are the first key_count letters
# A state is (row, column, keys held as a bitmask); BFS finds the fewest moves.
start = (start_row, start_col, 0)
visited = {start}
queue = collections.deque([start])
steps = 0
while queue:
for _ in range(len(queue)):
r, c, keys = queue.popleft()
if keys == all_keys:
return steps
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nr, nc = r + dr, c + dc
if nr < 0 or nr >= rows or nc < 0 or nc >= cols:
continue
cell = grid[nr][nc]
if cell == "#":
continue
if "A" <= cell <= "Z" and not keys & (1 << (ord(cell) - ord("A"))):
continue # a lock we have no key for
next_keys = keys
if "a" <= cell <= "z":
next_keys |= 1 << (ord(cell) - ord("a")) # pick up the key
state = (nr, nc, next_keys)
if state not in visited:
visited.add(state)
queue.append(state)
steps += 1
return -1