forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
39 lines (38 loc) · 1.09 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
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
unordered_set<string> s(deadends.begin(), deadends.end());
if (s.count("0000")) return -1;
if (target == "0000") return 0;
queue<string> q{{"0000"}};
s.insert("0000");
int ans = 0;
while (!q.empty()) {
++ans;
for (int n = q.size(); n > 0; --n) {
string p = q.front();
q.pop();
for (string t : next(p)) {
if (target == t) return ans;
if (!s.count(t)) {
q.push(t);
s.insert(t);
}
}
}
}
return -1;
}
vector<string> next(string& t) {
vector<string> res;
for (int i = 0; i < 4; ++i) {
char c = t[i];
t[i] = c == '0' ? '9' : (char) (c - 1);
res.push_back(t);
t[i] = c == '9' ? '0' : (char) (c + 1);
res.push_back(t);
t[i] = c;
}
return res;
}
};