Skip to content

Practice Shortest Path to Get All Keys

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#864
LeetCode Problem

Shortest Path to Get All Keys

Problem Statement

In grid, . is open space, # is a wall, @ is the starting cell, lowercase letters are keys, and uppercase letters are locks. Move one cell horizontally or vertically per step without crossing walls or leaving the grid. Entering a key cell collects it; a lock can be crossed only after collecting the matching lowercase key. For some k from 1 through 6, there is exactly one key and lock for each of the first k letters. Return the minimum moves needed to collect all keys, or -1 if impossible.

Source: Shortest Path to Get All Keys on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
grid = ["@.a..","###.#","b.A.B"]
Output
8

# Example 2

Input
grid = ["@..aA","..B#.","....b"]
Output
6

# Example 3

Input
grid = ["@Aa"]
Output
-1

Constraints

m == grid.length
n == grid[i].length
1 <= m, n <= 30
grid[i][j] is either an English letter, '.', '#', or '@'.
There is exactly one '@' in the grid.
The number of keys in the grid is in the range [1, 6].
Each key in the grid is unique.
Each key in the grid has a matching lock.

Related LeetCode Problems

Practice more problems similar to Shortest Path to Get All Keys.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.