Skip to content

Commit 3ae0e8d

Browse files
authored
Create 752. Open the Lock
1 parent b25732a commit 3ae0e8d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

752. Open the Lock

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution
2+
{
3+
public:
4+
int openLock(vector<string>& deadends, string target)
5+
{
6+
int operations = 0;
7+
unordered_set<string> dead, vis;
8+
9+
for(auto &deadend : deadends) dead.insert(deadend);
10+
if(dead.count("0000")) return -1;
11+
12+
queue<string> q;
13+
q.push("0000");
14+
vis.insert("0000");
15+
16+
while(q.size())
17+
{
18+
int sz = q.size();
19+
while(sz--)
20+
{
21+
string cur_state = q.front();q.pop();
22+
if(cur_state == target) return operations;
23+
for(int i = 0; i < 4; i++)
24+
{
25+
string new_state = cur_state;
26+
new_state[i] == '9' ? new_state[i] = '0' : new_state[i]++;
27+
if(!vis.count(new_state) and !dead.count(new_state))
28+
q.push(new_state), vis.insert(new_state);
29+
30+
new_state = cur_state;
31+
new_state[i] == '0' ? new_state[i] = '9' : new_state[i]--;
32+
if(!vis.count(new_state) and !dead.count(new_state))
33+
q.push(new_state), vis.insert(new_state);
34+
}
35+
}
36+
operations++;
37+
}
38+
return -1;
39+
}
40+
};

0 commit comments

Comments
 (0)