由于这个问题,涉及了很多知识,例如数据结构里面的哈希表,c++中的迭代器,因此,需要对于每一个疑惑逐一击破。
问题描述
参考答案
1 class Solution {
2 public:
3 int openLock(vector<string>& deadends, string target) {
4 unordered_set<string> dds(deadends.begin(), deadends.end());
5 unordered_set<string> visited;
6 queue<string> bfs;
7 string init = "0000";
8 if (dds.find(init) != dds.end()) return -1;
9 visited.insert("0000");
10 bfs.push("0000");
11 int res = 0;
12 while (!bfs.empty()) {
13 int sz = bfs.size();
14 for (int i = 0; i < sz; i++) {
15 string t = bfs.front(); bfs.pop();
16 vector<string> nbrs = move(nbrStrs(t));
17 for (auto s : nbrs) {
18 if (s == target) return ++res;
19 if (visited.find(s) != visited.end()) continue;
20 if (dds.find(s) == dds.end()) {
21 bfs.push(s);
22 visited.insert(s);
23 }
24 }
25 }
26 ++res;
27 }
28 return -1;
29 }
30
31
32 vector<string> nbrStrs(string key) {
33 vector<string> res;
34 for (int i = 0 ; i < 4; i++) {
35 string tmp = key;
36 tmp[i] = (key[i] - '0' + 1) % 10 + '0';
37 res.push_back(tmp);
38 tmp[i] = (key[i] - '0' - 1 + 10) % 10 + '0';
39 res.push_back(tmp);
40 }
41 return res;
42 }
43 };
补充知识
迭代器
正如我们知道的,程序中包含了大量的迭代,这些迭代都是在循环中进行的,比如for。
迭代(Iteration):是一种行为,对于某个特定容器,进行遍历的行为。
可迭代对象(Iterable):是一个容器,例如set,list,vector等等,一堆数据装在里面,而这个容器可以进行迭代操作。
那什么是迭代器(iterator)呢?
迭代器,就好像是一个可以供人们操作的装置对象,其中包含了数据,以及可以进行操作的按钮(例如c++中的begin,end等等[1]),这样我们可以很方便的使用并且操作打包好的数据。
另外还有一个问题,比如下面这个例子[2]:
std::vector<int> v;
for (vector<int>::iterator iter = v.begin(); iter != v.end(); ++iter)
{
// do someting with iter
}
v 能懂,是一个vector。vector<int> 类型的 iterator 也可以懂,但什么是 v.begin() ?
[1] 的解释是返回幵始迭代器。what the fxxk? 什么是开始迭代器?难道迭代器不是可以操纵的对象么?我查了很多的中文网站和博客,似乎都没有很理想的解释。后来查到了它的英文解释:begin() function is used to return an iterator pointing to the first element of the vector container.
这样就清楚好多了, v.begin() 是一个迭代器,特殊的是,它是指向容器中第一个元素的迭代器。
另外,也要注意 v.end() ,它也是迭代器,但它是 指向容器最后元素的 下一个位置的 迭代器。
使用例子[3]:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// declaration of vector container
vector<int> myvector{ 1, 2, 3, 4, 5 };
// using end() to print vector
for (auto it = myvector.begin() ; it != myvector.end(); ++it)
cout << ' ' << *it;
return 0;
}
输出为:
1 2 3 4 5
另外,不用费心考虑iteator的类型,直接使用auto即可
insert & find
[1]: http://c.biancheng.net/view/409.html
[2]:https://qinglinmao8315.github.io/c++/2018/03/07/how-std-vector-end-work.html
[3]: https://www.geeksforgeeks.org/vectorbegin-vectorend-c-stl/