-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path752. Open the Lock.cpp
32 lines (32 loc) · 1.32 KB
/
752. Open the Lock.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
class Solution {
public:
// https://leetcode.com/problems/open-the-lock/discuss/1250580/C%2B%2BJavaPython-BFS-Level-Order-Traverse-Clean-and-Concise
int openLock(vector<string>& deadends, string target) {
unordered_set<string> deadSet(deadends.begin(), deadends.end());
if (deadSet.count("0000")) return -1;
queue<string> q({"0000"});
for (int steps = 0; !q.empty(); ++steps) {
for (int i = q.size(); i > 0; --i) {
auto curr = q.front(); q.pop();
if (curr == target) return steps;
for (auto nei : neighbors(curr)) {
if (deadSet.count(nei)) continue;
deadSet.insert(nei); // Marked as visited
q.push(nei);
}
}
}
return -1;
}
vector<string> neighbors(const string& code) {
vector<string> result;
for (int i = 0; i < 4; i++) {
for (int diff = -1; diff <= 1; diff += 2) {
string nei = code;
nei[i] = (nei[i] - '0' + diff + 10) % 10 + '0';
result.push_back(nei);
}
}
return result;
}
};