07. Shortest Path to Get All Keys
You are given an $m \times n$ grid where lowercase letters 'a'-'f' are keys, uppercase letters 'A'-'F' are locks, '#' is a wall, and '@' is starting position. Return the minimum number of moves to acquire all keys.
How It Works & Algorithmic Design
Solves using BFS State Space Traversal with Bitmasking:
- Key Bitmasking: Identify total key count $K$. Goal state bitmask is
(1 << K) - 1. - Visited Set 3D State: Track
visited[r][c][bitmask]to allow revisiting grid cells when carrying new key sets. - BFS Queue Entry:
(r, c, bitmask, steps). - Cell Evaluation:
- Step onto key
'a'-'f': updatenewMask = bitmask | (1 << (char - 'a')). - Step onto lock
'A'-'F': allowed if(bitmask & (1 << (char - 'A'))) !== 0. - Reaching
newMask === goalMask: returnsteps + 1instantly.
- Step onto key
Why This Approach Works Best
Bitmask state representation transforms multi-key path finding into a clean shortest path BFS graph search in $O(m \times n \times 2^K)$ time.
Example Walkthrough
["@.a..","###.#","b.A.B"]
2 keys ('a','b') and 2 locks ('A','B').
Collect 'a' -> move down to 'b' -> unlock 'A' and 'B'.
8 total steps.
8
Minimum steps.
Answer: Shortest Path All Keys Bitmask BFS implementation
function shortestPathAllKeys(grid) {
const m = grid.length, n = grid[0].length;
let startR = 0, startC = 0, keyCount = 0;
for (let r = 0; r < m; r++) {
for (let c = 0; c < n; c++) {
const ch = grid[r][c];
if (ch === '@') { startR = r; startC = c; }
else if (ch >= 'a' && ch <= 'f') keyCount++;
}
}
const targetMask = (1 << keyCount) - 1;
const queue = [[startR, startC, 0, 0]];
const visited = new Set([`${startR},${startC},0`]);
const dirs = [[1,0],[-1,0],[0,1],[0,-1]];
while (queue.length) {
const [r, c, mask, steps] = queue.shift();
if (mask === targetMask) return steps;
for (const [dr, dc] of dirs) {
const nr = r + dr, nc = c + dc;
if (nr < 0 || nc < 0 || nr >= m || nc >= n || grid[nr][nc] === '#') continue;
const ch = grid[nr][nc];
let newMask = mask;
if (ch >= 'a' && ch <= 'f') newMask |= (1 << (ch.charCodeAt(0) - 97));
if (ch >= 'A' && ch <= 'F' && !(mask & (1 << (ch.charCodeAt(0) - 65)))) continue;
const keyState = `${nr},${nc},${newMask}`;
if (!visited.has(keyState)) {
visited.add(keyState);
queue.push([nr, nc, newMask, steps + 1]);
}
}
}
return -1;
}Traverse grid via BFS storing position and key bitmask to reach all keys in minimal steps.
Use bitmask to record collected keys efficiently.
Visited tracking requires
[row, col, keyMask]tuple state.Guarantees shortest path moves using BFS traversal.