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 - Grid Navigation Problem@.a.####.#b.A.BStartKey aKey bLock ALock BGoal: Collect all keys (a, b)Constraint: Need key to pass lockFind shortest path using BFSOutput: 8 moves (shortest path to collect keys a and b)
Understanding the Visualization
1
Input Grid
Grid with start '@', keys (lowercase), locks (uppercase), walls '#'
2
BFS Search
Find shortest path collecting all keys while respecting lock constraints
3
Output
Minimum moves to collect all keys, or -1 if impossible
Key Takeaway
🎯 Key Insight: Use BFS with state (position + keys_collected) to find optimal path while respecting lock constraints
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