[leetcode]752. Open the Lock

162 篇文章 0 订阅
53 篇文章 0 订阅

[leetcode]752. Open the Lock


Analysis

2019要开心鸭—— [每天刷题并不难0.0]

You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’. The wheels can rotate freely and wrap around: for example we can turn ‘9’ to be ‘0’, or ‘0’ to be ‘9’. Each move consists of turning one wheel one slot.

The lock initially starts at ‘0000’, a string representing the state of the 4 wheels.

You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.
在这里插入图片描述

Explanation:

用bfs列举出每一种可能出现的状态,然后删掉deadend里面的状态,直到找到target状态

Implement

class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        set<string> deadends1(deadends.begin(), deadends.end());
        if(deadends1.count("0000"))
            return -1;
        if(target == "0000")
            return 0;
        queue<string> mq;
        set<string> have;
        mq.push("0000");
        int res = 0;
        while(!mq.empty()){
            int sz = mq.size();
            for(int k=0; k<sz; k++){
                string cur = mq.front();
                mq.pop();
                for(int i=0; i<4; i++){
                    string tmp = cur;
                    tmp[i] = (cur[i]-'0'+1)%10+'0';
                    if(tmp == target)
                        return ++res;
                    if(!deadends1.count(tmp) && !have.count(tmp))
                        mq.push(tmp);
                    have.insert(tmp);
                    tmp[i] = (cur[i]-'0'-1+10)%10+'0';
                    if(tmp == target)
                        return ++res;
                    if(!deadends1.count(tmp) && !have.count(tmp))
                        mq.push(tmp);
                    have.insert(tmp);
                }
            }
            res++;
        }
        return -1;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值