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 <= grid.length <= 30
1 <= grid[0].length <= 30
grid[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.
Approach #1: C++. [BFS]
class Solution {
public:
int shortestPathAllKeys(vector<string>& grid) {
int m = grid.size();
int n = grid[0].size();
queue<int> q;
vector<vector<vector<int>>> seen(m, vector<vector<int>>(n, vector<int>(64, 0)));
int allKeys = 0; //Init
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
const char c = grid[i][j];
if (c == '@') {
q.push((i << 16) | (j << 8));
seen[i][j][0] = 1;
} else if (c >= 'a' && c <= 'f') {
allKeys |= (1 << (c - 'a'));
}
}
} int steps = 0;
vector<int> dirs = {-1, 0, 1, 0, -1}; while (!q.empty()) {
int size = q.size();
while (size--) {
int cur = q.front(); q.pop();
int x = cur >> 16;
int y = (cur >> 8) & 0xFF;
int keys = cur & 0xFF; if (keys == allKeys) return steps; for (int i = 0; i < 4; ++i) {
int xx = x + dirs[i];
int yy = y + dirs[i+1];
int curKeys = keys;
if (xx < 0 || xx >= m || yy < 0 || yy >= n) continue;
const char c = grid[xx][yy];
if (c == '#') continue;
if (c >= 'A' && c <= 'F' && !(keys & (1 << (c - 'A')))) continue;
if (c >= 'a' && c <= 'f') curKeys |= 1 << (c - 'a');
if (seen[xx][yy][curKeys]) continue;
seen[xx][yy][curKeys] = 1;
q.push((xx << 16) | (yy << 8) | curKeys);
}
}
steps++;
} return -1;
}
};
Analysis:
seen[x][y][keys] : To store the position and the number of keys. If this state don't be traveled we can do next step, otherwise we skip this state.
allKeys : To represent the keys which we will collect in this problem. In this problem we use six binary numbers to represent all the keys at difference bit.
such as : a -> 1 so it will be represented by 000001 and f -> f - 'a' = 6 so it will be represent by 100000. If we have the keys of a and f so we can use 100001 to represent that.
queue<int> q : To simulation the BFS.
864. Shortest Path to Get All Keys的更多相关文章
- [LeetCode] 864. Shortest Path to Get All Keys 获得所有钥匙的最短路径
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@& ...
- [Swift]LeetCode864. 获取所有钥匙的最短路径 | Shortest Path to Get All Keys
We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@& ...
- 最短路径遍历所有的节点 Shortest Path Visiting All Nodes
2018-10-06 22:04:38 问题描述: 问题求解: 本题要求是求遍历所有节点的最短路径,由于本题中是没有要求一个节点只能访问一次的,也就是说可以访问一个节点多次,但是如果表征两次节点状态呢 ...
- [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 ...
- hdu-----(2807)The Shortest Path(矩阵+Floyd)
The Shortest Path Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others ...
- zoj 2760 How Many Shortest Path 最大流
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 Given a weighted directed graph ...
- The Shortest Path in Nya Graph
Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...
- hdu 3631 Shortest Path(Floyd)
题目链接:pid=3631" style="font-size:18px">http://acm.hdu.edu.cn/showproblem.php?pid=36 ...
- Shortest Path(思维,dfs)
Shortest Path Accepts: 40 Submissions: 610 Time Limit: 4000/2000 MS (Java/Others) Memory Limit: ...
随机推荐
- Py修行路 python基础(六)前期基础整理
计算机中,有且仅有CPU具有执行权限,能够执行指令的只有CPU! 人在应用程序上输入的文字或文本,叫做明文! 在屏幕上输入或是输出的是字符,计算机保存的是 有字符编码的 二进制数. 变量赋值规则:例如 ...
- Linux - 创建用户的相关文件
创建一个用户会与 6 个文件相关 /etc/passwd 储存了所有用户的相关信息 第一行中,从左往右 root 为用户名,: 为分隔符,x 为密码,0 为 uid,0 为 gid,root 为用户的 ...
- springboot成神之——监视器
Spring Boot 的监视器 依赖 配置 书写监视控制器 常用的一些内置endpoint 定义actuator/info特殊endpoint actuator/shutdown需要post请求才能 ...
- ngnix 403 forbidden的解决办法
1.在网站根目录下新建文件index.html.index.php. 2.主要是修改nginx的配置文件nginx.conf权限为755即可访问.
- leetcode766
本题经过一下午的思考,终于解出来了.使用的是层次遍历的思想. class Solution { public: bool isToeplitzMatrix(vector<vector<in ...
- Minimum Sum of Array(map)
You are given an array a consisting of n integers a1, ..., an. In one operation, you can choose 2 el ...
- Lyx/LaTeX笔记04---插入伪代码
1 可用的宏包 常用的排版伪代码包有clrscode, algorithm, algorithmic, algorithmicx, algorithm2e 2 clrscode clrscode是著名 ...
- 尝试在centos5下运行phantomjs2
在redhat5上运行plantomjs 2,出现如下错误 bin/phantomjs: /lib64/libz.so.1: no version information available (req ...
- laravel Redis缓存
首先在app/config/cache.php配置文件下改变一下缓存的驱动方式改为redis composer require predis/predis 先安装conposer的扩展安装包 然后在c ...
- jquery on事件在IE8下失效的一种情况,及解决方法/bootstrap空间绑定控件事件不好用
同事在复制bootstrap中的select控件之后,发现用$('.selectpicker').selectpicker();刷新下拉框控件不好使,后来发现是用原生js克隆的方法obj.cloneN ...