KatInterview

Collect Keys on a Grid with Locked Doors

Dynamic ProgrammingAuto-graded · 17 test cases
HardAuto-gradedDynamic Programmingdynamic programmingbitmaskgrid

Last updated

Tests grid-path DP where the traveler must collect keys to unlock doors, requiring bitmask state to track which keys have been picked up.

Collect Keys on a Grid with Locked Doors

You are given a rectangular grid of characters. A robot starts at the top-left cell (0, 0) and wants to reach the bottom-right cell (rows-1, cols-1).

Each cell contains one of the following characters:

CharacterMeaning
'.'Empty — always passable
'#'Wall — impassable
'a'–'f'Key — passable; picking it up adds it to the robot's key-ring
'A'–'F'Door — passable only if the robot already carries the matching lowercase key
'S'Start cell (0, 0) — treated as empty
'E'End cell (rows-1, cols-1) — treated as empty

The robot may move up, down, left, or right one cell per step. It may revisit cells. When the robot enters a key cell it automatically picks up that key (a key already held is simply ignored). A door cell whose key is not held is impassable.

Your task: return the minimum number of steps to travel from S to E, or -1 if no such path exists.

Notes

  • Keys used are only the lowercase letters 'a' through 'f' (at most 6 distinct keys).
  • The grid contains at most 6 distinct key types (but may contain 0–6).
  • The start and end cells may coincide (a 1×1 grid): return 0 in that case.
  • The grid is guaranteed to have 'S' at (0, 0) and 'E' at (rows-1, cols-1).

Constraints

  • 1 ≤ rows, cols ≤ 20
  • 1 ≤ rows × cols ≤ 400
  • Grid contains only '.', '#', 'a'–'f', 'A'–'F', 'S', 'E'
  • At most 6 distinct lowercase key letters appear in the grid.
  • The robot starts with no keys.

Examples

Example 1

Input: min_steps_collect_keys(['S', 'E'])

Output: -1

Example 2

Input: min_steps_collect_keys(['S.', 'aA', '.E'])

Output: -1

Example 3

Input: min_steps_collect_keys(['S#E'])

Output: -1

Hints

Hint 1

The state space is (row, col, key_bitmask). Encode which keys the robot holds as a bitmask of up to 6 bits — this keeps the total number of states at most 20 × 20 × 64 = 25,600, which is tiny.

Hint 2

Use BFS (not DP with relaxation) because every step costs 1; BFS guarantees the first time a state is reached it is reached in the minimum number of steps.

Hint 3

When you step onto a key cell, compute the new bitmask by OR-ing the current mask with that key's bit. When you try to step onto a door cell, check whether the corresponding key bit is set in the current mask before allowing the move.