-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0752.OpenTheLock.cpp
More file actions
58 lines (48 loc) · 1.38 KB
/
0752.OpenTheLock.cpp
File metadata and controls
58 lines (48 loc) · 1.38 KB
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
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
// TODO: A more a* approach would be cooler.
set<string>
deadendSet(deadends.begin(), deadends.end()),
activeSet, usedSet;
activeSet.emplace("0000");
usedSet.emplace("0000");
// Early exits.
if (deadendSet.find("0000") != deadendSet.end()) return -1;
if (target == "0000") return 0;
// Find total steps.
int steps = 0;
string newString;
const int checks[] = { 9, 1 };
set<string> newActiveSet;
while (!activeSet.empty()) {
// Update steps.
steps++;
// Find target / Create new active set.
newActiveSet.clear();
for (const string& str : activeSet) {
// Move a wheel.
for (int i = 0; i < 4; i++) {
for (int j = 0; j < sizeof(checks) / sizeof(*checks); j++) {
// Create new combo.
newString = str;
newString[i] = (((newString[i] + checks[j]) - '0') % 10) + '0';
// Check against target.
if (newString == target) return steps;
// Check if already used.
if (usedSet.find(newString) != usedSet.end()) continue;
usedSet.emplace(newString);
// Check if deadend.
if (deadendSet.find(newString) != deadendSet.end()) continue;
// Add to active set.
newActiveSet.emplace(newString);
}
}
}
// Update active set.
activeSet = newActiveSet;
}
// Unable to find.
return -1;
}
};