forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
57 lines (53 loc) · 1.59 KB
/
Solution2.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
52
53
54
55
56
57
class Solution {
public:
unordered_set<string> s;
string start;
string target;
int openLock(vector<string>& deadends, string target) {
if (target == "0000") return 0;
for (auto d : deadends) s.insert(d);
if (s.count("0000")) return -1;
this->start = "0000";
this->target = target;
return bfs();
}
int bfs() {
unordered_map<string, int> m1;
unordered_map<string, int> m2;
m1[start] = 0;
m2[target] = 0;
queue<string> q1{{start}};
queue<string> q2{{target}};
while (!q1.empty() && !q2.empty()) {
int t = q1.size() <= q2.size() ? extend(m1, m2, q1) : extend(m2, m1, q2);
if (t != -1) return t;
}
return -1;
}
int extend(unordered_map<string, int>& m1, unordered_map<string, int>& m2, queue<string>& q) {
for (int n = q.size(); n > 0; --n) {
string p = q.front();
int step = m1[p];
q.pop();
for (string t : next(p)) {
if (s.count(t) || m1.count(t)) continue;
if (m2.count(t)) return step + 1 + m2[t];
m1[t] = step + 1;
q.push(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;
}
};