864 Shortest Path to Get All Keys
1. Question
Input: ["@.a.#","###.#","b.A.B"]
Output: 8Input: ["@..aA","..B#.","....b"]
Output: 62. Implementation
3. Time & Space Complexity
Last updated
Input: ["@.a.#","###.#","b.A.B"]
Output: 8Input: ["@..aA","..B#.","....b"]
Output: 6Last updated
class Solution {
public int shortestPathAllKeys(String[] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
int m = grid.length, n = grid[0].length();
int allKeys = 0;
Queue<Integer> queue = new LinkedList();
int[][][] visited = new int[m][n][64];
// Find the initial state and the number of keys
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
char c = grid[i].charAt(j);
if (c == '@') {
queue.add((i << 16) | (j << 8));
visited[i][j][0] = 1;
}
else if (c >= 'a' && c <= 'f') {
allKeys |= (1 << (c - 'a'));
}
}
}
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int steps = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int curState = queue.remove();
int row = curState >> 16;
int col = ((curState >> 8) & 0xff);
int keys = curState & 0xff;
// Found all the keys
if (keys == allKeys) {
return steps;
}
for (int [] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
int nextKeys = keys;
if (nextRow < 0 || nextRow >= m || nextCol < 0 || nextCol >= n) continue;
char c = grid[nextRow].charAt(nextCol);
// Wall
if (c == '#') continue;
// Don't have the key to open the door
if (c >= 'A' && c <= 'F' && (nextKeys & (1 << (c - 'a'))) == 0) continue;
// Visited state
if (visited[nextRow][nextCol][nextKeys] == 1) continue;
// Update key
if (c >= 'a' && c <= 'f') {
nextKeys |= (1 << (c - 'a'));
}
queue.add((nextRow << 16) | (nextCol << 8) | nextKeys);
visited[nextRow][nextCol][nextKeys] = 1;
}
}
++steps;
}
return -1;
}
}