-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path12.2 752. Open the Lock
44 lines (41 loc) · 1.07 KB
/
12.2 752. Open the Lock
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
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
unordered_set<string> seen{begin(deadends), end(deadends)};
if (seen.count("0000"))
return -1;
if (target == "0000")
return 0;
int ans = 0;
queue<string> q{{"0000"}};
while (!q.empty()) {
++ans;
for (int sz = q.size(); sz > 0; --sz) {
string word = q.front();
q.pop();
for (int i = 0; i < 4; ++i) {
const char cache = word[i];
// increase i-th digit by 1
word[i] = word[i] == '9' ? '0' : word[i] + 1;
if (word == target)
return ans;
if (!seen.count(word)) {
q.push(word);
seen.insert(word);
}
word[i] = cache;
// decrease i-th digit by 1
word[i] = word[i] == '0' ? '9' : word[i] - 1;
if (word == target)
return ans;
if (!seen.count(word)) {
q.push(word);
seen.insert(word);
}
word[i] = cache;
}
}
}
return -1;
}
};