I started with plain BFS and the interviewer immediately asked what happens when the same cell is visited twice but with different keys collected.
Model the problem as a shortest path in a state space where each state is (position, set of collected keys). Use BFS to explore states level by level, since each move has uniform cost. When a key is collected, update the key set and unlock all doors of that color.
Pro tip: Mention that the number of keys is typically small, so bitmask representation is efficient. Also, discuss how to handle multiple keys of the same color—collecting one unlocks all doors of that color, so you only need to track which colors have been collected.
Represent each state as (row, col, key_mask), where key_mask is a bitmask of collected key colors. This captures both position and which doors are unlocked.
Start BFS from the initial position with an empty key mask. Use a queue and a visited set to avoid revisiting states.
For each state, consider moving up, down, left, right. If the neighbor is a wall, skip. If it's a door, only proceed if the corresponding key bit is set. If it's a key, update the key mask by setting the bit for that color.
Maintain distance from start. When the goal cell is reached, return the distance. If BFS exhausts all states without reaching the goal, return -1.
Use a 3D visited array or a set of encoded integers to track visited states efficiently. Bitmask allows up to 32 key colors.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.