Leetcode #864: Shortest Path to Get All Keys
In this guide, we solve Leetcode #864 Shortest Path to Get All Keys in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Bit Manipulation, Breadth-First Search, Array, Matrix
Intuition
We need level-by-level exploration or shortest steps, which is ideal for BFS.
A queue naturally models the frontier of the search.
Approach
Push initial nodes into a queue and expand in layers.
Track visited nodes to prevent cycles.
Steps:
- Initialize queue with start nodes.
- Process level by level.
- Track visited nodes.
Example
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.
Python Solution
class Solution:
def shortestPathAllKeys(self, grid: List[str]) -> int:
m, n = len(grid), len(grid[0])
# Find the starting point (si, sj)
si, sj = next((i, j) for i in range(m) for j in range(n) if grid[i][j] == '@')
# Count the number of keys
k = sum(v.islower() for row in grid for v in row)
dirs = (-1, 0, 1, 0, -1)
q = deque([(si, sj, 0)])
vis = {(si, sj, 0)}
ans = 0
while q:
for _ in range(len(q)):
i, j, state = q.popleft()
# If all keys are found, return the current step count
if state == (1 << k) - 1:
return ans
# Search in the four directions
for a, b in pairwise(dirs):
x, y = i + a, j + b
nxt = state
# Within boundary limits
if 0 <= x < m and 0 <= y < n:
c = grid[x][y]
# It's a wall, or it's a lock but we don't have the key for it
if (
c == '#'
or c.isupper()
and (state & (1 << (ord(c) - ord('A')))) == 0
):
continue
# It's a key
if c.islower():
# Update the state
nxt |= 1 << (ord(c) - ord('a'))
# If this state has not been visited, enqueue it
if (x, y, nxt) not in vis:
vis.add((x, y, nxt))
q.append((x, y, nxt))
# Increment the step count
ans += 1
return -1
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.