|
| 1 | +// Runtime: 6 ms (Top 99.86%) | Memory: 10.30 MB (Top 99.86%) |
| 2 | + |
1 | 3 | class Solution {
|
2 | 4 | public:
|
3 |
| - void setPermutations(const string& s, queue<pair<string, int>>& q, int count) { |
4 |
| - for (int i=0; i<4; i++) { |
5 |
| - int j = s[i]-'0'; |
6 |
| - char b = (10+j-1)%10 + '0', n = (10+j+1)%10 + '0'; |
7 |
| - auto tmp = s; tmp[i]=b; |
8 |
| - q.push({tmp, count+1}); |
9 |
| - tmp = s; tmp[i]=n; |
10 |
| - q.push({tmp, count+1}); |
11 |
| - } |
12 |
| - } |
13 | 5 | int openLock(vector<string>& deadends, string target) {
|
14 |
| - unordered_set<string> deadies(deadends.begin(), deadends.end()); |
15 |
| - queue<pair<string, int>> q({{"0000", 0}}); |
16 |
| - while (!q.empty()) { |
17 |
| - auto t = q.front(); |
18 |
| - q.pop(); |
19 |
| - if (deadies.count(t.first)) |
20 |
| - continue; |
21 |
| - if (t.first==target) |
22 |
| - return t.second; |
23 |
| - deadies.insert(t.first); |
24 |
| - setPermutations(t.first, q, t.second); |
| 6 | + if (target == "0000") return 0; |
| 7 | + queue<int> queue; |
| 8 | + queue.push(0); |
| 9 | + bool seen[10000]{false}; |
| 10 | + for (auto& d : deadends) |
| 11 | + seen[stoi(d)] = true; |
| 12 | + int targ = stoi(target); |
| 13 | + if (seen[0]) return -1; |
| 14 | + for (int turns = 1; queue.size(); turns++) { |
| 15 | + int qlen = queue.size(); |
| 16 | + for (int i = 0; i < qlen; i++) { |
| 17 | + int curr = queue.front(); |
| 18 | + queue.pop(); |
| 19 | + for (int j = 1; j < 10000; j *= 10) { |
| 20 | + int mask = curr % (j * 10) / j, |
| 21 | + masked = curr - (mask * j); |
| 22 | + for (int k = 1; k < 10; k += 8) { |
| 23 | + int next = masked + (mask + k) % 10 * j; |
| 24 | + if (seen[next]) continue; |
| 25 | + if (next == targ) return turns; |
| 26 | + seen[next] = true; |
| 27 | + queue.push(next); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
25 | 31 | }
|
26 | 32 | return -1;
|
27 | 33 | }
|
|
0 commit comments