首页 > 其他 > 详细

打开转盘锁

时间:2020-03-22 12:57:25      阅读:184      评论:0      收藏:0      [点我收藏+]

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

 

 

思路:
广度优先

打开转盘锁

原文:https://www.cnblogs.com/bailuoxi/p/12544621.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!