Shortest Path to Get All Keys - Problem

You're a treasure hunter navigating through an ancient dungeon! ๐Ÿ—๏ธ You've discovered a grid-based dungeon filled with keys and locked doors, and your goal is to collect all the keys using the minimum number of moves.

The dungeon layout consists of:

  • '.' - Empty spaces you can walk through
  • '#' - Walls that block your path
  • '@' - Your starting position
  • 'a'-'f' - Keys you need to collect (lowercase letters)
  • 'A'-'F' - Locked doors that require corresponding keys (uppercase letters)

Movement rules:

  • You can move in 4 cardinal directions (up, down, left, right)
  • You cannot move outside the grid or through walls
  • Walking over a key automatically picks it up
  • You can only pass through a locked door if you have its corresponding key

There are exactly 1-6 pairs of keys and locks, using the first k letters of the alphabet in order.

Goal: Return the minimum number of moves to collect all keys, or -1 if impossible.

Input & Output

simple_maze.py โ€” Basic Example
$ Input: grid = ["@.a.#", "###.#", "b.A.B"]
โ€บ Output: 8
๐Ÿ’ก Note: Start at @, move right to collect key 'a' (2 moves), go down and around to collect key 'b' (6 more moves total), then return to open door 'A'. Total: 8 moves to collect both keys.
impossible_case.py โ€” No Solution
$ Input: grid = ["@..aA", "..#..", "....."]
โ€บ Output: -1
๐Ÿ’ก Note: Key 'a' is available, but there's no corresponding lowercase 'A' door or path to collect all required keys. Since the problem states there must be exactly one key for each lock, this represents an impossible scenario.
single_key.py โ€” Edge Case
$ Input: grid = ["@...a"]
โ€บ Output: 4
๐Ÿ’ก Note: Simple case with one key. Start at position 0, move right 4 times to reach and collect the key 'a'. Since there's only one key to collect, we're done in 4 moves.

Visualization

Tap to expand
@.a.####.#b.A.BBFS State Tracking000Start: No keys001Key 'a' collected011Keys 'a' + 'b'111All keys! โœ“Shortest Path Found!BFS guarantees optimality
Understanding the Visualization
1
Initialize
Start at '@' with empty key collection (bitmask = 000)
2
BFS Level 1
Explore adjacent cells, collect any keys found
3
State Tracking
Track (row, col, key_bitmask) to avoid revisiting same situations
4
Door Logic
Check key requirements before passing through locked doors
5
Success Check
When key_bitmask equals (1<<k)-1, we have all keys!
Key Takeaway
๐ŸŽฏ Key Insight: Transform the problem into a state-space search where each state is (position + key collection). BFS ensures we find the shortest path efficiently!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(m*n*2^k)

We have m*n positions and 2^k possible key states (k โ‰ค 6), each state processed once

n
2n
โœ“ Linear Growth
Space Complexity
O(m*n*2^k)

Need to store visited states and BFS queue, both bounded by total number of possible states

n
2n
โšก Linearithmic Space

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 โ‰ค m, n โ‰ค 30
  • grid[i][j] is a lowercase letter, uppercase letter, '.', '#', or '@'
  • The number of keys is in the range [1, 6]
  • There is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid
  • 1 โ‰ค k โ‰ค 6
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
43.7K Views
High Frequency
~25 min Avg. Time
1.8K 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