-
Notifications
You must be signed in to change notification settings - Fork 0
/
752. Open the Lock.cpp
51 lines (42 loc) · 1.27 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
48
49
50
51
class Solution {
public:
void fillNeighbors(queue<string>& que, string& curr, unordered_set<string>& dead) {
for(int i = 0; i<4; i++) {
char ch = curr[i];
char dec = ch=='0' ? '9' : ch-1;
char inc = ch=='9' ? '0' : ch+1;
curr[i] = dec;
if(!dead.count(curr)) {
dead.insert(curr);
que.push(curr);
}
curr[i] = inc;
if(!dead.count(curr)) {
dead.insert(curr);
que.push(curr);
}
curr[i] = ch;
}
}
int openLock(vector<string>& deadends, string target) {
unordered_set<string> dead(begin(deadends), end(deadends));
string start = "0000";
if(dead.count(start))
return -1;
queue<string> que;
que.push(start);
int level = 0;
while(!que.empty()) {
int n = que.size();
while(n--) {
string curr = que.front();
que.pop();
if(curr == target)
return level;
fillNeighbors(que, curr, dead);
}
level++;
}
return -1;
}
};