剑指 Offer II 109. 开密码锁

这是一个关于解决开密码锁问题的算法实现。代码中使用了广度优先搜索(BFS)策略,通过一个队列来存储当前状态,并利用unordered_set避免重复访问和检查死路。算法首先排除已知的死路,然后从初始状态开始,逐层遍历所有可能的密码组合,直到找到目标密码。get_neighboards函数用于生成当前密码的所有相邻状态。如果找到目标密码,返回步数,否则返回-1表示无法到达。
摘要由CSDN通过智能技术生成

 链接:剑指 Offer II 109. 开密码锁

题解:

class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        std::unordered_set<std::string> table(deadends.begin(), deadends.end());
        // 面向异常设计
        if (table.find("0000") != table.end()) {
            return -1;
        }
        // 面向异常设计
        if (target == "0000") {
            return 0;
        }
        std::queue<std::pair<std::string, int>> que;
        que.push(make_pair("0000", 0));
        std::unordered_set<std::string> visited;
        visited.insert("0000");
        while (!que.empty()) {
            auto f = que.front();
            que.pop();
            for (auto& neighboard : get_neighboards(f.first)) {
                if (visited.find(neighboard) != visited.end() || table.find(neighboard) != table.end()) {
                    continue;
                }
                if (neighboard == target) {
                    return f.second+1;
                }
                que.push(std::make_pair(neighboard, f.second+1));
                visited.insert(neighboard);
            }
        }
        return -1;
    }
private:
    std::vector<std::string> get_neighboards(std::string& cur) {
        auto next = [](char a)->char {
            return a == '9' ? '0' : a+1;
        };
        auto prev = [](char a)->char {
            return a == '0' ? '9' : a-1;
        };
        std::vector<std::string> result;
        for (int i = 0; i < cur.size(); ++i) {
            char c = cur[i];
            cur[i] = next(c);
            result.push_back(cur);
            cur[i] = prev(c);
            result.push_back(cur);
            cur[i] = c;
        }
        return result;
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值