LeetCode 864. Shortest Path to Get All Keys

864. Shortest Path to Get All Keys

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[0].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.

Approach

题目大意: 求最短路径拿到所有钥匙
解题思路:求最短路径可以bfs求得,关键是如何标记状态避免重复访问,一般bfs或dfs就简单标记访问过和没访问过的状态,但是这道题要考虑此时已有钥匙的状态,也就是当你为了拿一把钥匙而走到死胡同,此时就要回走,因为你比之前多了把钥匙,所以状态不一样,可以回走。我们怎么标记状态呢,我们用位来标记有几把钥匙的状态,然后dfs和bfs都可以求最短路径,但bfs简单一点,开销也没那么大,dfs还要递归,不断求最小值。

Code

struct node {
    int x, y, step, key;

    node(int _x, int _y, int _step, int _key) : x(_x), y(_y), step(_step), key(_key) {
    }
};
class Solution {
public:
    int shortestPathAllKeys(vector<string> grid) {
        int sti = -1, stj = -1, n = grid.size(), m = grid[0].size(), ans = 0;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == '@') {
                    sti = i, stj = j;
                }
                if (grid[i][j] >= 'a' && grid[i][j] <= 'f')ans |= (1 << (grid[i][j] - 'a'));
            }
        }
        if (sti == -1 || stj == -1)return 0;
        vector<vector<vector<bool>>> vis(n, vector<vector<bool>>(m, vector<bool>(64, false)));
        vector<vector<int>> dir{{1, -1, 0,  0},
                                {0, 0,  -1, 1}};
        queue<node> q;
        q.push(node(sti, stj, 0, 0));
        while (!q.empty()) {
            node o = q.front();
            q.pop();
            if (o.key == ans)return o.step;
            for (int i = 0; i < 4; i++) {
                int newx = o.x + dir[0][i], newy = o.y + dir[1][i], newk = o.key;
                if (newx < 0 || newx >= n || newy < 0 || newy >= m ||
                    grid[newx][newy] == '#' ||
                    (grid[newx][newy] >= 'A' && grid[newx][newy] <= 'F' && !(newk & (1 << (grid[newx][newy] - 'A')))))
                    continue;
                if (grid[newx][newy] >= 'a' && grid[newx][newy] <= 'f')newk |= (1 << (grid[newx][newy] - 'a'));
                if (vis[newx][newy][newk])continue;
                vis[newx][newy][newk] = true;
                q.push(node(newx, newy, o.step + 1, newk));
            }
        }
        return -1;
    }
};
上一篇:递归和回溯_leetcode-floodfill


下一篇:牛客寒假算法基础集训营5 I 炫酷镜子