forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
51 lines (48 loc) · 1.31 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
unordered_set<string> s(deadends.begin(), deadends.end());
if (s.count(target) || s.count("0000")) return -1;
if (target == "0000") return 0;
unordered_set<string> visited;
queue<string> q;
q.push("0000");
int step = 0;
while (!q.empty())
{
++step;
for (int i = 0, n = q.size(); i < n; ++i)
{
string status = q.front();
q.pop();
for (auto t : get(status))
{
if (visited.count(t) || s.count(t)) continue;
if (t == target) return step;
q.push(t);
visited.insert(t);
}
}
}
return -1;
}
char prev(char c) {
return c == '0' ? '9' : (char) (c - 1);
}
char next(char c) {
return c == '9' ? '0' : (char) (c + 1);
}
vector<string> get(string& t) {
vector<string> res;
for (int i = 0; i < 4; ++i)
{
char c = t[i];
t[i] = prev(c);
res.push_back(t);
t[i] = next(c);
res.push_back(t);
t[i] = c;
}
return res;
}
};