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
.
Example 1:
Input: grid = ["@.a.#","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.
思路:这题跟Shortest Path Visiting All Nodes
是一模一样的题目,就是pos会重复visit,但是每次visite的状态是不一样的,收集的key是不一样的,所以用(i, j, state)来表示visit,state是用1<< (key - 'a)来表示的,代表收集了多少个key;
class Solution {
public int shortestPathAllKeys(String[] grid) {
int m = grid.length;
int n = grid[0].length();
int finalstate = 0;
int startX = -1; int startY = -1;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
char c = grid[i].charAt(j);
if(c == '@') {
startX = i;
startY = j;
} else if('a' <= c && c <= 'f') {
finalstate |= 1 << (c - 'a');
}
}
}
Queue<int[]> queue = new LinkedList<>();
HashSet<String> visited = new HashSet<>();
queue.offer(new int[] {startX, startY, 0});
visited.add(startX + " " + startY + " " + 0);
int[][] dirs = new int[][] {{0,-1},{0,1},{1,0},{-1,0}};
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] node = queue.poll();
int x = node[0];
int y = node[1];
int curstate = node[2];
if(curstate == finalstate) {
return step;
}
for(int[] dir: dirs) {
int nextstate = curstate;
int nx = x + dir[0];
int ny = y + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n && grid[nx].charAt(ny) != '#') {
char c = grid[nx].charAt(ny);
// collect keys;
if('a' <= c && c <= 'f') {
nextstate |= 1 << (c - 'a');
}
// if next cube is lock, but i don't have keys, i still can not go;
if('A' <= c && c <= 'Z' && ((nextstate >> (c - 'A')) & 1) == 0) {
continue;
}
if(!visited.contains(nx + " "+ ny + " " + nextstate)) {
visited.add(nx + " "+ ny + " " + nextstate);
queue.offer(new int[] {nx, ny, nextstate});
}
}
}
}
step++;
}
return -1;
}
}