Shortest Path to Get All Keys
Master this topic with zero to advance depth.
Shortest Path to Get All Keys
You are given an m x n grid grid where:
'.'is an empty cell.'#'is a wall.'@'is the starting point.- lowercase letters are keys.
- uppercase letters are 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 through a wall. If you walk over a key, you pick it up. If you walk over a lock and have the matching key, you can pass through it.
Return the lowest number of moves to acquire all keys. If it's impossible, return -1.
Visual Representation
Grid:
@ . a . #
# # # . #
b . A . B
Starting at @. Path:
1. Pick 'a'
2. Use 'a' to open 'A'
3. Pick 'b'
Done! Return shortest path length.Examples
Shortest path to pick up all keys 'a' and 'b'.
Level III: Optimal (BFS with State - Bitmask)
Intuition
The 'state' of our BFS is not just our position (r, c), but also which keys we possess. We can represent the set of obtained keys as a bitmask. This turns the problem into a standard shortest path BFS in a state space of (r, c, mask).
Thought Process
- Find start position
@and count total number of keysK. - Target mask is
(1 << K) - 1. - Queue stores
(r, c, mask, distance). visited[r][c][mask]tracks seen states.- In each step:
- If current cell is a key, update
newMask = mask | (1 << (key - 'a')). - If
newMask == targetMask, returndist. - If current cell is a lock and we don't have the key, skip.
- Standard 4-direction BFS flow.
- If current cell is a key, update
Pattern: BFS with State Bitmasking
Detailed Dry Run
2 keys. Target mask = 11 (3). Start (0,0) mask 00.
- Reach 'a' (0,2). Mask = 01.
- Reach 'A' (2,2). Lock 'A' (bit 0) matches mask bit 0. Passage allowed.
- Reach 'b' (2,0). Mask = 11. Target reached!
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.