[LeetCode] 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 Kletters 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 <= grid.length <= 301 <= grid[0].length <= 30grid[i][j]contains only'.','#','@','a'-``'f``'and'A'-'F'- The number of keys is in
[1, 6]. Each key has a different letter and opens exactly one lock.
这道题给了我们一个迷宫,其中的点表示可通过的位置,井号表示墙,不能通过。小写字母表示钥匙,大写字母表示门,只有拿到了对应的钥匙才能通过门的地方,有点红白机游戏的感觉。问我们收集到所有的钥匙需要的最小步数,当无法收到所有钥匙的时候,返回 -1。对于迷宫遍历找最小步数的题,应该并不陌生,基本都是用 BFS 来解的。这里虽然没有一个固定的终点位置,但也是有终止条件的,那就是收集到所有的钥匙。这道题好就好在对钥匙进行了一些限定,最多有6把,最少有1把,而且都是按字母顺序出现的,就是说只有一把钥匙的时候,一定是a,两把的话一定是a和b。我们需要保存所有当前已经获得的钥匙,并且还要随时查询是否已经获得了某个特定的钥匙,还需要查询是否已经获得了所有的钥匙。由于之前说了知道了钥匙的个数,就能确定是哪些钥匙,这样就可以对钥匙进行编号,钥匙a编为0,同理,b,c,d,e,f 分别编为 1,2,3,4,5。最简单的实现就是用一个长度为k的 boolean 数组,获得了某个钥匙就标记为 true,查询某个钥匙是否存在就直接在数组中对应位置查询即可,判断是否获得所有钥匙就线性遍历一下数组即可,由于最多就6把钥匙,所以遍历也很快。当然,若我们想秀一波技巧,也可以将钥匙编码成二进制数,对应位上的0和1表示该钥匙是存在,比如二进制数 111111 就表示六把钥匙都有了,而 100111 就表示有钥匙 a,d,e 和f,这样查询某个钥匙或查询所有钥匙的时间复杂度都是常数级了,既省了空间又省了时间,岂不美哉?!
分析到这里,基本上难点都 cover 了,可以准备写代码了。整体框架还是经典的 BFS 写法,再稍加改动即可。这里的队列 queue 不能只放位置信息,还需要放当前的钥匙信息,因为到达不同的位置获得的钥匙个数可能是不同的,二维的位置信息编码成一个整数,再加上钥匙的整数,组成一个 pair 对儿放到队列中。由于参数中没有事先告诉我们起点的位置,所以需要先遍历一遍整个迷宫,找到@符号,将位置和当前钥匙信息加入到 queue 中。为了避免死循环,BFS 遍历是需要记录已经访问过的位置的,这里的状态当然也要加入当前钥匙的信息,为了简单起见,将其编码成一个字符串,前半部分放位置编码成的整数,中间加个下划线,后面放钥匙信息的整数,组成的字符串放到 HashSet 中即可。遍历的过程中同时还要统计钥匙的个数,有了总个数 keyCnt,就能知道拿到所有钥匙后编码成的整数。在 while 循环,采用层序遍历的机制,对于同一层的结点,分别取出位置信息和钥匙信息,此时先判断下是否已经拿到所有钥匙了,是的话直接返回当前步数 res。否则就要检测其四个相邻位置,需要注意的是,对于每个相邻位置,一定要重新取出之前的钥匙信息,否则一旦钥匙信息修改了而没有重置的话,直接到同一层的其他结点可能会引起错误。取出的邻居结点的位置要先判断是否越界,还要判断是否为墙,是的话就直接跳过。若是门的话,要看当前是否有该门对应的钥匙,有的话才能通过。若遇到了钥匙,则需要修改钥匙信息。这些都完成了之后,将当前的位置和钥匙信息编码成一个字符串,看 HashSet 是否已经有了这个状态,没有的话,则加入 HashSet,并同时加入 queue,每当一层结点遍历完成后,结果 res 自增1即可,参见代码如下:
```
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 = 'a' && grid[i][j] 0; --i) {
int t = q.front().first, curKeys = q.front().second; q.pop();
if (curKeys == (1 = m || y = n) continue;
char c = grid[x][y];
if (c == '#') continue;
if (c >= 'A' && c > (c - 'A')) & 1) == 0) continue;
if (c >= 'a' && c
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
[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)
[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, "@& ...
- [LeetCode] 847. Shortest Path Visiting All Nodes 访问所有结点的最短路径
An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1) is given as graph. graph.lengt ...
- LeetCode 1091. Shortest Path in Binary Matrix
原题链接在这里:https://leetcode.com/problems/shortest-path-in-binary-matrix/ 题目: In an N by N square grid, ...
- [Swift]LeetCode864. 获取所有钥匙的最短路径 | Shortest Path to Get All Keys
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@& ...
- LeetCode 847. Shortest Path Visiting All Nodes
题目链接:https://leetcode.com/problems/shortest-path-visiting-all-nodes/ 题意:已知一条无向图,问经过所有点的最短路径是多长,边权都为1 ...
- [Leetcode]847. Shortest Path Visiting All Nodes(BFS|DP)
题解 题意 给出一个无向图,求遍历所有点的最小花费 分析 1.BFS,设置dis[status][k]表示遍历的点数状态为status,当前遍历到k的最小花费,一次BFS即可 2.使用DP 代码 // ...
- LeetCode 1293. Shortest Path in a Grid with Obstacles Elimination
题目 非常简单的BFS 暴搜 struct Node { int x; int y; int k; int ans; Node(){} Node(int x,int y,int k,int ans) ...
- leetcode 847. Shortest Path Visiting All Nodes 无向连通图遍历最短路径
设计最短路径 用bfs 天然带最短路径 每一个状态是 当前的阶段 和已经访问过的节点 下面是正确但是超时的代码 class Solution: def shortestPathLength(self, ...
- [MIT6.006] 19. Daynamic Programming I: Fibonacci, Shortest Path 动态规划I:斐波那契,最短路径
这节课讲动态规划的内容,动态规划是一种通用且有效的算法设计思路,它的主要成分是"子问题"+"重用".它可以用于斐波那契和最短路径等问题的求解上. 一.斐波那契 ...
随机推荐
- Flink是如何实现exactly-once语义的
转自:https://blog.csdn.net/xianpanjia4616/article/details/86375224 最少一次:断了之后 重新执行 再去重 严格一次:根据检查点,再执行一次 ...
- python xpath图片爬取
import requests from urllib.request import urlretrieve from lxml import etree headers = { 'User-Agen ...
- [LeetCode#178]Rank Scores
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ra ...
- 《数据结构》《C++程序设计》《计算机组成原理》中的英语名词
一.数据结构 data 数据data element 数据元素data item 数据项data object 数据对象data structure 数据结构ADT (Abstruct Date Ty ...
- 2019-11-29-WPF-禁用实时触摸
原文:2019-11-29-WPF-禁用实时触摸 title author date CreateTime categories WPF 禁用实时触摸 lindexi 2019-11-29 10:20 ...
- C# 改变控制台背景颜色
之前查找静态构造函数相关的问题无意间碰到的一个问题.改变控制台的背景颜色. static void Main(string[] args) { //设置绿色 Console.BackgroundCol ...
- 在.NET Core 3.0 Preview上使用Windows窗体设计器
支持使用基于Windows窗体应用程序的.NET Core 3.0(预览)的Windows窗体设计器 介绍 截至撰写本文时,Microsoft和社区目前正在测试.NET Core 3.0.如果您在.N ...
- sql 动态行转列 (2005及以上版本)
表数据: sql: --pivot方案 sql 2005及以上版本 ) Set @sql=(Select DISTINCT ','+ N'[' +pref_name+N']' FROM dbo.Pop ...
- Spring Boot @EnableAutoConfiguration解析
刚做后端开发的时候,最早接触的是基础的spring,为了引用二方包提供bean,还需要在xml中增加对应的包<context:component-scan base-package=" ...
- Vim操作:打开文件
1.打开文件并定位到某一行 vim +20 vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php # 定位至第20行 2 ...