[LeetCode] Shortest Path to Get All Keys

864. Shortest Path to Get All Keys

You are given an m x n grid grid where:

  • ‘.’ is an empty cell.
  • ‘#’ is a wall.
  • ‘@’ is the starting point.
  • Lowercase letters represent keys.
  • Uppercase letters represent locks.

You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.

If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its 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 is impossible, return -1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {

public:
int shortestPathAllKeys(vector<string>& grid) {
int n = grid.size(), m = grid[0].length(), key = 0;
unordered_map<char, int> keymp;
queue<array<int,3>> q;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(grid[i][j] == '@') {
q.push({i,j,0});
} else if(islower(grid[i][j])) {
keymp[grid[i][j]] = key++;
}
}
}
vector<vector<vector<bool>>> vis(n, vector<vector<bool>>(m, vector<bool>(1<<key, false)));
if(!key) return 0;
vis[q.front()[0]][q.front()[1]][q.front()[2]] = true;
int res = 1;
int dy[4] = {-1,0,1,0}, dx[4] = {0,1,0,-1};
while(!q.empty()) {
int sz = q.size();
while(sz--) {
auto [y, x, mask] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and !vis[ny][nx][mask] and grid[ny][nx] != '#') {
if(islower(grid[ny][nx])) { //key
vis[ny][nx][mask] = true;
int nmask = mask | (1<<keymp[grid[ny][nx]]);
if(nmask == ((1<<key) - 1)) return res;
q.push({ny,nx,nmask});
} else if(isupper(grid[ny][nx])) { //lock
char low = grid[ny][nx] - 'A' + 'a';
if(keymp.count(low) and (1<<keymp[low]) & mask) {
vis[ny][nx][mask] = true;
q.push({ny,nx,mask});
}
} else { // dot
vis[ny][nx][mask] = true;
q.push({ny,nx,mask});
}

}
}
}
res++;
}
return -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/16/PS/LeetCode/shortest-path-to-get-all-keys/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.