# 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.

`class Solution { public: int shortestPathAllKeys(vector& grid) { int m = grid.size(), n = grid[0].size(), keyCnt = 0, res = 0; queue> q; unordered_set visited; vector dirX{-1, 0, 1, 0}, dirY{0, 1, 0, -1}; for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (grid[i][j] == '@') { q.push({i * n + j, 0}); visited.insert(to_string(i * n + j) + "_0"); } if (grid[i][j] >= 'a' && grid[i][j] <= 'f') ++keyCnt; } } while (!q.empty()) { for (int i = q.size(); i > 0; --i) { int t = q.front().first, curKeys = q.front().second; q.pop(); if (curKeys == (1 << keyCnt) - 1) return res; for (int k = 0; k < 4; ++k) { int x = t / n + dirX[k], y = t % n + dirY[k], keys = curKeys; if (x < 0 || x >= m || y < 0 || y >= n) continue; char c = grid[x][y]; if (c == '#') continue; if (c >= 'A' && c <= 'F' && ((keys >> (c - 'A')) & 1) == 0) continue; if (c >= 'a' && c <= 'f') keys |= 1 << (c - 'a'); string str = to_string(x * n + y) + "_" + to_string(keys); if (!visited.count(str)) { visited.insert(str); q.push({x * n + y, keys}); } } } ++res; } return -1; } };`
Github 同步地址:

https://github.com/grandyang/leetcode/issues/864

https://leetcode.com/problems/shortest-path-to-get-all-keys/

https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/146878/Java-BFS-Solution

https://leetcode.com/problems/shortest-path-to-get-all-keys/discuss/146941/C%2B%2B-BFS-with-current-key-recorded-visited-map-(12ms)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation