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

# 864. Shortest Path to Get All Keys

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.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.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] = GRAY;
distances[startRow][startColumn] = 0;
int[][] directions = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
queue.offer(new int[]{startRow, startColumn, 0});
while (!queue.isEmpty()) {
int[] cell = queue.poll();
int row = cell, column = cell, keys = cell;
int distance = distances[row][column][keys];
if (keys == targetKeys)
return distance;
for (int[] direction : directions) {
int newRow = row + direction, newColumn = column + direction;
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;
}
}

• // OJ: https://leetcode.com/problems/shortest-path-to-get-all-keys/
// Time: O(MN)
// Space: O(MN)
class Solution {
int getKey(int x, int y, int keys) {
return 10000 * x + 100 * y + keys;
}
tuple<int, int, int> parseKey(int key) {
return { key / 10000, key % 10000 / 100, key % 100 };
}
public:
int shortestPathAllKeys(vector<string>& A) {
int M = A.size(), N = A.size(), keys = 0, step = 0, dirs = { {0,1},{0,-1},{1,0},{-1,0} }, sx = 0, sy = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] >= 'a' && A[i][j] <= 'f') keys |= 1 << (A[i][j] - 'a');
else if (A[i][j] == '@') sx = i, sy = j;
}
}
int init = getKey(sx, sy, keys);
queue<int> q{ {init} };
unordered_set<int> seen{init};
while (q.size()) {
int cnt = q.size();
while (cnt--) {
auto [x, y, keys] = parseKey(q.front());
q.pop();
if (keys == 0) return step;
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy, next = 0;
if (a < 0 || a >= M || b < 0 || b >= N || A[a][b] == '#') continue;
if (A[a][b] >= 'A' && A[a][b] <= 'F') {
int k = A[a][b] - 'A';
if (keys >> k & 1) continue; // we don't have to corresponding key yet.
next = getKey(a, b, keys);
} else if (A[a][b] >= 'a' && A[a][b] <= 'f') {
int k = A[a][b] - 'a';
next = getKey(a, b, keys & ~(1 << k));
} else {
next = getKey(a, b, keys);
}
if (seen.count(next)) continue;
seen.insert(next);
q.push(next);
}
}
step++;
}
return -1;
}
};

• print("Todo!")