Shortest Path to Get All Keys — LeetCode 864 Python Solution
HardBit ManipulationBreadth-First SearchArrayMatrix
- Problem
- #864
- Pattern
- Bit Manipulation
- Reading time
- 7 min
- Source
- leetcode.com
The problem
You are given an m x n grid grid where: '.' is an empty cell. '#' is a wall.
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
Python
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n \times 2^k) |
| Space | O(m \times n \times 2^k) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 864. Shortest Path to Get All Keys is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 864. Shortest Path to Get All Keys?
- LeetCode 864. Shortest Path to Get All Keys is rated Hard on LeetCode.
- What is the time complexity of LeetCode 864. Shortest Path to Get All Keys?
- The Python solution on this page runs in O(m \times n \times 2^k).
- What is the space complexity of LeetCode 864. Shortest Path to Get All Keys?
- The Python solution on this page uses O(m \times n \times 2^k) auxiliary space.
- What topics does LeetCode 864. Shortest Path to Get All Keys cover?
- LeetCode 864. Shortest Path to Get All Keys is tagged Bit Manipulation, Breadth-First Search, Array and Matrix on LeetCode.