题目链接

初始状态:"0000"
如果初始状态等于 targrt 的状态,返回 0
如果初始状态在终止状态里则返回 -1
最后就是进行宽搜 $BFS$,如果能到达目标状态则返回操作次数,否则返回 -1
class Solution {
public:
int openLock(vector<string>& deadends, string target) {
string star = "0000";
if(target == star) return 0;
unordered_set<string> s;
for(auto& x : deadends) s.insert(x);
if(s.count(star)) return -1;
unordered_map<string,int> dis;
dis[star] = 0;
queue<string> q;
q.push(star);
while(!q.empty())
{
string now = q.front();
q.pop();
for(int i = 0; i < 4; i++){
for(int j = -1; j <= 1; j += 2){
string t = now;
t[i] = (t[i] - '0' + j + 10)%10 + '0';
if(!s.count(t) && !dis.count(t)){
dis[t] = dis[now] + 1;
if(t == target) return dis[t];
q.push(t);
}
}
}
}
return -1;
}
};