KatInterview

Minimum Steps to Collect All Keys in a Grid Maze

Trees & GraphsAuto-graded · 17 test cases
HardAuto-gradedTrees & Graphsgraphsbfsgrid

Last updated

Tests BFS shortest path on a grid where state must encode both position and the set of collected keys, requiring multi-dimensional state space exploration.

Minimum Steps to Collect All Keys in a Grid Maze

You are given a rectangular grid maze represented as a list of strings. Each cell is one of the following characters:

CharacterMeaning
'.'Open passage
'#'Wall (impassable)
'@'Starting position
'a'–'f'A key (lowercase letter) — walking onto it collects it
'A'–'F'A locked door (uppercase letter) — passable only if you already hold the matching key ('a' for 'A', etc.)

Your task is to find the minimum number of steps needed to collect every key present in the grid, starting from '@'. You may move one step at a time — up, down, left, or right. You cannot step outside the grid boundaries.

Return the minimum number of steps, or -1 if it is impossible to collect all keys.

Notes

  • There is always exactly one starting position '@'.
  • Keys are the lowercase letters actually present in the grid; there may be 0 to 6 of them ('a' through 'f').
  • Doors whose matching key is not present in the grid are treated as open passages (you will never need the missing key, so they do not block you).
  • You do not need to return to the starting position.
  • Once all keys are collected you stop immediately (you do not have to walk through every door).

Constraints

  • 1 ≤ len(grid) ≤ 30 (number of rows)
  • 1 ≤ len(grid[0]) ≤ 30 (number of columns)
  • All rows have the same length.
  • The grid contains exactly one '@'.
  • The grid contains at most 6 distinct keys ('a'–'f').
  • Characters are only those listed in the table above.

Examples

Example 1

Input: min_steps_collect_keys(['@.a.#', '###.#', 'b.A.B'])

Output: 8

Example 2

Input: min_steps_collect_keys(['@..aA', '......', '......', 'b#####', '....B.'])

Output: 9

Example 3

Input: min_steps_collect_keys(['@'])

Output: 0