https://juejin.im/post/5d5e8e8351882555f46b1717
c++
class Solution { public: int openLock(vector<string>& deadends, string target) { //hashset unordered_set<string> deadset(deadends.begin(), deadends.end()); if(deadset.find("0000") != deadset.end()) return -1; queue<string> q; q.push("0000"); int count = 0; while(!q.empty()){ int size = q.size(); while(size-- > 0){ string tmp = q.pop(); string tmp1 ,tmp2; if(tmp == target) return count; for (int i = 0; i< 4; i++){ tmp1 = tmp, tmp2 = tmp; tmp1[i] = tmp1[i] == ‘9‘ ? ‘0‘ : tmp1[i] + 1; if(deadset.find(tmp1) == deadset.end()){ q.push(tmp1); } tmp2[i] = tmp2[i] == ‘0‘ ? ‘9‘ : tmp2[i] - 1; if(deadset.find(tmp2) == deadset.end()){ q.push(tmp2); } } } count++; } return -1; } };
思路:
广度优先
原文:https://www.cnblogs.com/bailuoxi/p/12544621.html