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 #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的更多相关文章

  1. [LeetCode] 864. Shortest Path to Get All Keys 获得所有钥匙的最短路径

    We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@& ...

  2. [Swift]LeetCode864. 获取所有钥匙的最短路径 | Shortest Path to Get All Keys

    We are given a 2-dimensional grid. "." is an empty cell, "#" is a wall, "@& ...

  3. 最短路径遍历所有的节点 Shortest Path Visiting All Nodes

    2018-10-06 22:04:38 问题描述: 问题求解: 本题要求是求遍历所有节点的最短路径,由于本题中是没有要求一个节点只能访问一次的,也就是说可以访问一个节点多次,但是如果表征两次节点状态呢 ...

  4. [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 ...

  5. hdu-----(2807)The Shortest Path(矩阵+Floyd)

    The Shortest Path Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others ...

  6. zoj 2760 How Many Shortest Path 最大流

    题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=1760 Given a weighted directed graph ...

  7. The Shortest Path in Nya Graph

    Problem Description This is a very easy problem, your task is just calculate el camino mas corto en ...

  8. hdu 3631 Shortest Path(Floyd)

    题目链接:pid=3631" style="font-size:18px">http://acm.hdu.edu.cn/showproblem.php?pid=36 ...

  9. Shortest Path(思维,dfs)

    Shortest Path  Accepts: 40  Submissions: 610  Time Limit: 4000/2000 MS (Java/Others)  Memory Limit: ...

随机推荐

  1. Oray.com花生壳路由器配置注意

    当路由器不链接wan口,只链接lan口时,此路由器其实就是当做一个无线交换机使用了,在此种情况下,花生壳登录会失败,因为花生壳本身也认为这设备不是路由器.

  2. vs2010一运行就报错deven.exe assert failure 解决方法,卸载系统中.netFramework最新版本的(简体中文)

    vs2010一运行就报错deven.exe assert failure 解决方法,卸载系统中.netFramework最新版本的(简体中文)

  3. JavaScript语言基础-基本数据类型与对象类型

  4. 虚拟机之 LNMP

    LNMP就是Linux nginx mysql php 一.mysql 下载安装mysql转至 LAMP (点击“LAMP”即可跳转) 也可以从快照跳转至mysql安装ok 二.php 下载同上, 1 ...

  5. IDEA中快速排除maven依赖

    选中该模块 点击show dependenties 切换试图 选中要排除的依赖,右击 选择Execlude,然后选择需要在哪个模块添加排除依赖 完成

  6. Bootstrap 学习资料

    1.Bootstrap中文文档 2.Bootstrap3.1.1 DEMO 3.Bootstrap教程 4.Sco.js--Bootstrap javascript组件的增强版 如果,您认为阅读这篇博 ...

  7. TensorFlow模型保存和提取方法

    一.TensorFlow模型保存和提取方法 1. TensorFlow通过tf.train.Saver类实现神经网络模型的保存和提取.tf.train.Saver对象saver的save方法将Tens ...

  8. solrCloud选举leader的逻辑分析

    First call *setup(ElectionContext) to ensure the election process is in it'd.    Next calljoinElecti ...

  9. 04.webservice客户端调用

    不要求所有的元素都理解,真正做开发的时候,有一些必须是要用的. 以后我们做开发的时候服务访问点的集合就一个服务的访问点.服务访问点绑定了具体的一个服务类,绑定的这个东西它本身也是一个元素.往上找,四个 ...

  10. python小程序:备份文件

    设计程序,有以下步骤: 需要备份的文件和目录由一个列表指定. 备份应该保存在主备份目录中. 文件备份成一个zip文件. zip存档的名称是当前的日期和时间. 解决方案: 版本一: #!/usr/bin ...