-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path752-Open-the-Lock.cpp
47 lines (37 loc) · 1.12 KB
/
752-Open-the-Lock.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
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
string start = "0000";
unordered_set<string> dead(deadends.begin(), deadends.end());
unordered_set<string> visited;
if (dead.count(start)) {
return -1;
}
queue<string> q;
q.push(start);
visited.insert(start);
int level = 0;
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; ++i) {
string current = q.front();
q.pop();
if (current == target) {
return level;
}
for (int j = 0; j < 4; ++j) {
for (int d = -1; d <= 1; d += 2) {
string next = current;
next[j] = (next[j] - '0' + d + 10) % 10 + '0';
if (!visited.count(next) && !dead.count(next)) {
q.push(next);
visited.insert(next);
}
}
}
}
++level;
}
return -1;
}
};