Shortest Path to Get All Keys - Problem

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.

Return the lowest number of moves to acquire all keys. If it is impossible, return -1.

Input & Output

Example 1 — Basic Key Collection
$ Input: grid = ["@.a.#","###.#","b.A.B"]
Output: 8
💡 Note: Start at @, collect key 'a' (2 moves), go back to collect key 'b' (4 moves), then pass through locks A and B (2 more moves). Total: 8 moves.
Example 2 — Impossible Case
$ Input: grid = ["@..aA","..#..","....B"]
Output: -1
💡 Note: Cannot reach key 'b' needed for lock 'B', so impossible to collect all keys.
Example 3 — No Keys
$ Input: grid = ["@...","...."]
Output: 0
💡 Note: No keys to collect, so 0 moves needed.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 30
  • grid[i][j] is one of '@', '.', '#', or a letter
  • 1 ≤ number of keys ≤ 6

Visualization

Tap to expand
Shortest Path to Get All Keys INPUT @ . a . # # # # . # b . A . B @ Start a,b Keys A,B Locks # Wall grid = ["@.a.#", "###.#", "b.A.B"] Keys to collect: a, b (k=2) ALGORITHM (BFS) 1 Initialize BFS State = (x, y, keys_bitmask) Start: (0,0, 0b00) dist=0 2 Explore Neighbors 4 directions: up,down,left,right Skip walls and unmatched locks 3 Update Key State Pick up key: update bitmask key 'a': 0b01, key 'b': 0b10 4 Check Completion All keys: bitmask = 0b11 Return current distance BFS Queue States: (0,0,00) d=0 --> (0,1,00) d=1 (0,1,00) d=1 --> (0,2,01) d=2 [got a] (0,2,01) --> ... --> (2,0,11) d=8 Path: @ --> a --> A --> B --> b All keys collected at step 8! FINAL RESULT @ 2 a 2 A 2 B 2 b Move Breakdown @ to a: 2 moves (right, right) a to A: 2 moves (down, down) A to B: 2 moves (right, right) OUTPUT 8 [OK] Minimum moves found All 2 keys collected Final state: (2,0, 0b11) Key Insight: BFS with state = (position, keys_collected) explores all possible paths level by level. Using a bitmask for keys (e.g., 0b11 = both 'a' and 'b') efficiently tracks which keys we have. Time: O(m * n * 2^k) where k is number of keys. Space: O(m * n * 2^k) for visited states. TutorialsPoint - Shortest Path to Get All Keys | BFS with Bitmask
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen