-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution3.cpp
60 lines (57 loc) · 1.67 KB
/
Solution3.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
58
59
60
class Solution {
public:
string target;
int openLock(vector<string>& deadends, string target) {
if (target == "0000") return 0;
unordered_set<string> s(deadends.begin(), deadends.end());
if (s.count("0000")) return -1;
string start = "0000";
this->target = target;
typedef pair<int, string> PIS;
priority_queue<PIS, vector<PIS>, greater<PIS>> q;
unordered_map<string, int> dist;
dist[start] = 0;
q.push({f(start), start});
while (!q.empty()) {
PIS t = q.top();
q.pop();
string state = t.second;
int step = dist[state];
if (state == target) return step;
for (string& t : next(state)) {
if (s.count(t)) continue;
if (!dist.count(t) || dist[t] > step + 1) {
dist[t] = step + 1;
q.push({step + 1 + f(t), t});
}
}
}
return -1;
}
int f(string s) {
int ans = 0;
for (int i = 0; i < 4; ++i) {
int a = s[i] - '0';
int b = target[i] - '0';
if (a < b) {
int t = a;
a = b;
b = t;
}
ans += min(b - a, a + 10 - b);
}
return ans;
}
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;
}
};