慢慢写,慢慢感觉。
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
unordered_set<string> deadset(deadends.begin(),deadends.end());
if(deadset.find("0000") != deadset.end())
{
return -1;
}
queue<string> queueA;
queueA.push("0000");
unordered_set<string> visited;
visited.insert("0000");
int times = 0;
while(!queueA.empty())
{
int QueueNumber = queueA.size();
for(int i = 0 ; i < QueueNumber ; i++)
{
string stringA = queueA.front();
if(stringA == target)
{
return times;
}
queueA.pop();
for(int j = 0 ; j < 4 ; j++)
{
string stringAdd = stringA;
string stringSub = stringA;
stringAdd[j] = stringAdd[j]=='9'?'0':stringAdd[j]+1;
stringSub[j] = stringSub[j]=='0'?'9':stringSub[j]-1;
if(deadset.find(stringAdd) == deadset.end() && visited.find(stringAdd) == visited.end())
{
queueA.push(stringAdd);
visited.insert(stringAdd);
}
if(deadset.find(stringSub) == deadset.end() && visited.find(stringSub) == visited.end())
{
queueA.push(stringSub);
visited.insert(stringSub);
}
}
}
times++;
}
return -1;
}
};