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;
}
}
该博客介绍了一个基于网格的寻路问题,目标是在有限步数内收集所有钥匙。问题中,网格包含空地、墙、起始点、字母(表示钥匙和锁)。每个锁对应一把钥匙,且字母顺序与英语字母表一致。给出的解决方案是使用宽度优先搜索(BFS),用状态表示当前位置和已收集的钥匙,并避免走入已有锁但未拥有对应钥匙的位置。算法会记录已访问过的节点,直到找到收集所有钥匙的最短路径,若无法完成则返回-1。
1353

被折叠的 条评论
为什么被折叠?



