打开转盘锁

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;
        
        
    }
};
View Code

 

 

思路:
广度优先

posted @ 2020-03-22 11:21  谁给起个名  阅读(275)  评论(0)    收藏  举报