KatInterview

895. Shortest Path to Get All Keys

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the minimum number of moves to collect all keys in a grid. This is a classic shortest path problem on a graph. However, the state in this graph is not just the player's position (row, col). The ability to traverse the grid depends on the keys collected. For example, to pass through a lock 'A', we must possess key 'a'. Therefore, the state of our search must include both the current position and the set of keys currently held.

Solution

Shortest Path to Get All Keys in Python

from collections import deque

class Solution:
    def shortestPathAllKeys(self, grid: list[str]) -> int:
        m, n = len(grid), len(grid[0])
        
        q = deque()
        visited = set() # (row, col, mask)
        
        key_count = 0
        start_r, start_c = -1, -1
        
        # Find start position and count keys
        for r in range(m):
            for c in range(n):
                if grid[r][c] == '@':
                    start_r, start_c = r, c
                elif 'a' <= grid[r][c] <= 'f':
                    key_count += 1
        
        target_mask = (1 << key_count) - 1
        
        # Initial state: (row, col, mask)
        q.append((start_r, start_c, 0))
        visited.add((start_r, start_c, 0))
        
        steps = 0
        
        while q:
            level_size = len(q)
            for _ in range(level_size):
                r, c, mask = q.popleft()
                
                # Check if all keys are collected
                if mask == target_mask:
                    return steps
                
                # Explore neighbors
                for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                    nr, nc = r + dr, c + dc
                    
                    # Check bounds
                    if 0 <= nr < m and 0 <= nc < n:
                        cell = grid[nr][nc]
                        next_mask = mask
                        
                        # Wall
                        if cell == '#':
                            continue
                        
                        # Key
                        if 'a' <= cell <= 'f':
                            next_mask |= (1 << (ord(cell) - ord('a')))
                        
                        # Lock
                        elif 'A' <= cell <= 'F':
                            # Check if we have the key
                            if not (mask & (1 << (ord(cell) - ord('A')))):
                                continue
                        
                        # If state is not visited, add to queue
                        if (nr, nc, next_mask) not in visited:
                            visited.add((nr, nc, next_mask))
                            q.append((nr, nc, next_mask))
            
            steps += 1
            
        return -1

Shortest Path to Get All Keys in Java

class Solution {
    public int shortestPathAllKeys(String[] grid) {
        int m = grid.length;
        int n = grid[0].length();
        
        Queue<int[]> queue = new LinkedList<>(); // {row, col, mask}
        boolean[][][] visited = new boolean[m][n][64];
        
        int startR = 0, startC = 0, keyCount = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                char cell = grid[i].charAt(j);
                if (cell == '@') {
                    startR = i;
                    startC = j;
                } else if (cell >= 'a' && cell <= 'f') {
                    keyCount++;
                }
            }
        }
        
        int targetMask = (1 << keyCount) - 1;
        
        // Start BFS
        queue.offer(new int[]{startR, startC, 0});
        visited[startR][startC][0] = true;
        int steps = 0;
        
        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};
        
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
            for (int i = 0; i < levelSize; i++) {
                int[] current = queue.poll();
                int r = current[0];
                int c = current[1];
                int mask = current[2];
                
                // Check if we have collected all keys
                if (mask == targetMask) {
                    return steps;
                }
                
                // Explore neighbors
                for (int j = 0; j < 4; j++) {
                    int nr = r + dr[j];
                    int nc = c + dc[j];
                    
                    // Check bounds and walls
                    if (nr < 0 || nr >= m || nc < 0 || nc >= n || grid[nr].charAt(nc) == '#') {
                        continue;
                    }
                    
                    char cell = grid[nr].charAt(nc);
                    int nextMask = mask;
                    
                    // If it's a key, update the mask
                    if (cell >= 'a' && cell <= 'f') {
                        nextMask |= (1 << (cell - 'a'));
                    } 
                    // If it's a lock, check if we have the key
                    else if (cell >= 'A' && cell <= 'F') {
                        if (!((mask >> (cell - 'A')) & 1)) {
                            continue; // Don't have the key
                        }
                    }
                    
                    // If the new state hasn't been visited, add it to the queue
                    if (!visited[nr][nc][nextMask]) {
                        visited[nr][nc][nextMask] = true;
                        queue.offer(new int[]{nr, nc, nextMask});
                    }
                }
            }
            steps++;
        }
        
        return -1; // Impossible to collect all keys
    }
}

Shortest Path to Get All Keys in C++

class Solution {
public:
    int shortestPathAllKeys(vector<string>& grid) {
        int m = grid.size();
        int n = grid[0].size();
        
        queue<tuple<int, int, int>> q; // {row, col, mask}
        vector<vector<vector<bool>>> visited(m, vector<vector<bool>>(n, vector<bool>(64, false)));
        
        int start_r = 0, start_c = 0, key_count = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == '@') {
                    start_r = i;
                    start_c = j;
                } else if (grid[i][j] >= 'a' && grid[i][j] <= 'f') {
                    key_count++;
                }
            }
        }
        
        int target_mask = (1 << key_count) - 1;
        
        // Start BFS
        q.push({start_r, start_c, 0});
        visited[start_r][start_c][0] = true;
        int steps = 0;
        
        int dr[] = {-1, 1, 0, 0};
        int dc[] = {0, 0, -1, 1};
        
        while (!q.empty()) {
            int level_size = q.size();
            for (int i = 0; i < level_size; ++i) {
                auto [r, c, mask] = q.front();
                q.pop();
                
                // Check if we have collected all keys
                if (mask == target_mask) {
                    return steps;
                }
                
                // Explore neighbors
                for (int j = 0; j < 4; ++j) {
                    int nr = r + dr[j];
                    int nc = c + dc[j];
                    
                    // Check bounds and walls
                    if (nr < 0 || nr >= m || nc < 0 || nc >= n || grid[nr][nc] == '#') {
                        continue;
                    }
                    
                    char cell = grid[nr][nc];
                    int next_mask = mask;
                    
                    // If it's a key, update the mask
                    if (cell >= 'a' && cell <= 'f') {
                        next_mask |= (1 << (cell - 'a'));
                    } 
                    // If it's a lock, check if we have the key
                    else if (cell >= 'A' && cell <= 'F') {
                        if (!((mask >> (cell - 'A')) & 1)) {
                            continue; // Don't have the key
                        }
                    }
                    
                    // If the new state hasn't been visited, add it to the queue
                    if (!visited[nr][nc][next_mask]) {
                        visited[nr][nc][next_mask] = true;
                        q.push({nr, nc, next_mask});
                    }
                }
            }
            steps++;
        }
        
        return -1; // Impossible to collect all keys
    }
};

Shortest Path to Get All Keys in TypeScript

function shortestPathAllKeys(grid: string[]): number {
    const m = grid.length;
    const n = grid[0].length;

    const queue: [number, number, number][] = []; // [row, col, mask]
    const visited = new Set<string>(); // "r,c,mask"

    let keyCount = 0;
    let startR = -1, startC = -1;

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            const cell = grid[i][j];
            if (cell === '@') {
                startR = i;
                startC = j;
            } else if (cell >= 'a' && cell <= 'f') {
                keyCount++;
            }
        }
    }

    const targetMask = (1 << keyCount) - 1;

    // Start BFS
    queue.push([startR, startC, 0]);
    visited.add(`${startR},${startC},0`);
    let steps = 0;

    const dr = [-1, 1, 0, 0];
    const dc = [0, 0, -1, 1];

    while (queue.length > 0) {
        const levelSize = queue.length;
        for (let i = 0; i < levelSize; i++) {
            const [r, c, mask] = queue.shift()!;

            if (mask === targetMask) {
                return steps;
            }

            for (let j = 0; j < 4; j++) {
                const nr = r + dr[j];
                const nc = c + dc[j];

                if (nr < 0 || nr >= m || nc < 0 || nc >= n || grid[nr][nc] === '#') {
                    continue;
                }

                const cell = grid[nr][nc];
                let nextMask = mask;

                if (cell >= 'a' && cell <= 'f') {
                    nextMask |= (1 << (cell.charCodeAt(0) - 'a'.charCodeAt(0)));
                } else if (cell >= 'A' && cell <= 'F') {
                    if (!((mask >> (cell.charCodeAt(0) - 'A'.charCodeAt(0))) & 1)) {
                        continue;
                    }
                }

                const stateKey = `${nr},${nc},${nextMask}`;
                if (!visited.has(stateKey)) {
                    visited.add(stateKey);
                    queue.push([nr, nc, nextMask]);
                }
            }
        }
        steps++;
    }

    return -1;
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.