Skip to content

Commit 526be12

Browse files
committed
Runtime: 6 ms (Top 99.86%) | Memory: 10.30 MB (Top 99.86%)
1 parent fb19998 commit 526be12

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

scripts/algorithms/O/Open the Lock/Open the Lock.cpp

+27-21
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,33 @@
1+
// Runtime: 6 ms (Top 99.86%) | Memory: 10.30 MB (Top 99.86%)
2+
13
class Solution {
24
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-
}
135
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+
}
2531
}
2632
return -1;
2733
}

0 commit comments

Comments
 (0)