Formatted question description: https://leetcode.ca/all/864.html

864. Shortest Path to Get All Keys

Level

Hard

Description

We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@" is the starting point, ("a", "b", …) are keys, and ("A", "B", …) are locks.

We start at the starting point, and one move consists of walking one space in one of the 4 cardinal directions. We cannot walk outside the grid, or walk into a wall. If we walk over a key, we pick it up. We can’t walk over a lock unless we have the corresponding key.

For some 1 <= K <= 6, there is exactly one lowercase and one uppercase letter of the first K letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.

Return the lowest number of moves to acquire all keys. If it’s impossible, return -1.

Example 1:

Input: [”@.a.#”,”###.#”,”b.A.B”]

Output: 8

Example 2:

Input: [“@..aA”,”..B#.”,”….b”]

Output: 6

Note:

  1. 1 <= grid.length <= 30
  2. 1 <= grid[0].length <= 30
  3. grid[i][j] contains only '.', '#', '@', 'a'-'f' and 'A'-'F'
  4. The number of keys is in [1, 6]. Each key has a different letter and opens exactly one lock.

Solution

Create a 3D array from the original grid, where the three dimensions are the row, the column and the state of keys. Since there are at most 6 keys, there are at most 64 different states of keys. Find the starting point and do breadth first search from the starting point. If an empty cell or the starting point is met, simply move to the cell with the state of keys unchanged, if the cell with the state of keys has not been visited. If a key is met, move to the cell and update the state of keys. If a lock is met, it can be reached only if the corresponding key is available, so move to the cell if the corresponding key is available and the cell with the state of keys has not been visited.

If at one point, all keys are acquired, return the distance. If it is impossible to acquire all keys, return -1.

class Solution {
    public int shortestPathAllKeys(String[] grid) {
        final int STATES = 1 << 6;
        final int BLOCK = -1;
        final int WHITE = 0;
        final int GRAY = 1;
        final int BLACK = 2;
        int rows = grid.length, columns = grid[0].length();
        int startRow = -1, startColumn = -1;
        boolean flag = false;
        for (int i = 0; i < rows; i++) {
            String curRow = grid[i];
            for (int j = 0; j < columns; j++) {
                if (curRow.charAt(j) == '@') {
                    startRow = i;
                    startColumn = j;
                    flag = true;
                    break;
                }
            }
            if (flag)
                break;
        }
        int targetKeys = 0;
        for (int i = 0; i < rows; i++) {
            String curRow = grid[i];
            for (int j = 0; j < columns; j++) {
                char c = curRow.charAt(j);
                if (Character.isLetter(c) && c < 'a') {
                    int index = c - 'A';
                    targetKeys |= 1 << index;
                }
            }
        }
        int[][][] colors = new int[rows][columns][STATES];
        int[][][] distances = new int[rows][columns][STATES];
        for (int i = 0; i < rows; i++) {
            String curRow = grid[i];
            for (int j = 0; j < columns; j++) {
                char c = curRow.charAt(j);
                if (c == '#') {
                    for (int k = 0; k < STATES; k++)
                        colors[i][j][k] = BLOCK;
                }
                for (int k = 0; k < STATES; k++)
                    distances[i][j][k] = Integer.MAX_VALUE;
            }
        }
        colors[startRow][startColumn][0] = GRAY;
        distances[startRow][startColumn][0] = 0;
        int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
        Queue<int[]> queue = new LinkedList<int[]>();
        queue.offer(new int[]{startRow, startColumn, 0});
        while (!queue.isEmpty()) {
            int[] cell = queue.poll();
            int row = cell[0], column = cell[1], keys = cell[2];
            int distance = distances[row][column][keys];
            if (keys == targetKeys)
                return distance;
            for (int[] direction : directions) {
                int newRow = row + direction[0], newColumn = column + direction[1];
                if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns) {
                    char c = grid[newRow].charAt(newColumn);
                    if (c == '#')
                        continue;
                    else if (c == '.' || c == '@') {
                        if (colors[newRow][newColumn][keys] == WHITE) {
                            colors[newRow][newColumn][keys] = GRAY;
                            distances[newRow][newColumn][keys] = distance + 1;
                            queue.offer(new int[]{newRow, newColumn, keys});
                        }
                    } else if (Character.isLetter(c)) {
                        if (c >= 'a') {
                            int index = c - 'a';
                            int newKeys = keys | 1 << index;
                            if (colors[newRow][newColumn][newKeys] == WHITE) {
                                colors[newRow][newColumn][newKeys] = GRAY;
                                distances[newRow][newColumn][newKeys] = distance + 1;
                                queue.offer(new int[]{newRow, newColumn, newKeys});
                            }
                        } else {
                            int index = c - 'A';
                            int curKey = keys >> index & 1;
                            if (curKey == 1) {
                                if (colors[newRow][newColumn][keys] == WHITE) {
                                    colors[newRow][newColumn][keys] = GRAY;
                                    distances[newRow][newColumn][keys] = distance + 1;
                                    queue.offer(new int[]{newRow, newColumn, keys});
                                }
                            }
                        }
                    }
                }
            }
            colors[row][column][keys] = BLACK;
        }
        return -1;
    }
}

All Problems

All Solutions