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: ...
随机推荐
- 记录一下学习Android的小知识
目前要设计即时通讯的整体架构,包括服务端.Android.IOS.PC.平板等等系统,所以需要研究一下手机的实现方式,开始从Android入手,偶尔在这记录下小知识. ADT: 1.页面功能请求结构, ...
- Python3.x 常用的新特性
Python3.x 常用的新特性 print() 是函数,不是一个语句 raw_input()输入函数,改为 input() Python 3 对文本和二进制数据做了更为清晰的区分. 文本由unico ...
- git commit 提交的时候,出现*** Please tell me who you are. git config --global 。。。问题
$ git commit -a -m 'v6' *** Please tell me who you are. Run git config --global user.email "you ...
- 点击jQuery Mobile的按钮改变颜色
jquery-mobile-移动 我有这样的代码来改变点击一个按钮的颜色: $('.fav').live('click', function(e) { $(this).buttonMarkup({ t ...
- Python基础学习六 操作MySQL
python操作数据库,需要先安装模块 1.下载MySQL.Redis模块 2.解压后,在当前目录执行 python setup.py install 3.或是pycharm直接选择安装 import ...
- OSCache安装
OSCache是一个基于web应用的组件,他的安装工作主要是对web应用进行配置,大概的步骤如下: 1. 下载.解压缩OSCachehttps://java.net/downloads/oscache ...
- YII2 模型关联之 一对多
需求,一个用户有多篇文章全部查询出来 文章表 用户表 //首先查找出一个用户出来 $user=Users::find()->'])->one(); //第一个参数还是关联的模型,第二个依旧 ...
- js,javascript生成 UUID的四种方法
全局唯一标识符(GUID,Globally Unique Identifier)也称作 UUID(Universally Unique IDentifier) . GUID是一种由算法生成的二进制长度 ...
- 【总结整理】word使用技巧
Tab+Enter,在编过号以后,会自动编号段落 Ctrl + D调出字体栏,配合Tab+Enter全键盘操作吧 Ctrl + L 左对齐, Ctrl + R 右对齐, Ctrl + E 居中 Ctr ...
- selector在color和drawable目录下的区别
selector作为drawable资源时,放于drawable目录下,并且item指定android:drawable属性,引用使用@drawable而不是@color selector作为colo ...