Shortest Path to Get All Keys

HardGraphsbfs

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a grid as a list of equal-length strings. Each character is one of: - '@': the single starting cell - '.': an empty cell - '#': a wall - a lowercase letter 'a'-'f': a key - an uppercase letter 'A'-'F': a lock, which you can enter only once you hold the matching lowercase key Each move goes one cell up, down, left or right, and you cannot leave the grid or enter walls. Walking onto a key picks it up. If the grid has k keys, they are the first k letters of the alphabet, and each has exactly one matching lock. Return the fewest moves needed to collect **all** keys, or -1 if that is impossible.

Examples

Input: grid = ["@.a..","###.#","b.A.B"]
Output: 8
Walk right to key a (2 moves), go down and through lock A, then left to key b, for 8 moves total.
Input: grid = ["@..aA","..B#.","....b"]
Output: 6
Collect key a in 3 moves, step right through lock A, then walk down to key b, for 3 more moves.
Input: grid = ["@Aa"]
Output: -1
Lock A stands between the start and its only key.

Constraints

  • 1 <= rows, cols <= 30
  • `grid[i][j]` is one of `'@'`, `'.'`, `'#'`, `'a'`-`'f'`, `'A'`-`'F'`
  • There is exactly one `@` and between 1 and 6 keys.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More bfs problems