剑指 Offer II 109. 开密码锁

剑指 Offer II 109. 开密码锁_第1张图片

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

题解:

class Solution {
public:
    int openLock(vector& deadends, string target) {
        std::unordered_set table(deadends.begin(), deadends.end());
        // 面向异常设计
        if (table.find("0000") != table.end()) {
            return -1;
        }
        // 面向异常设计
        if (target == "0000") {
            return 0;
        }
        std::queue> que;
        que.push(make_pair("0000", 0));
        std::unordered_set 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 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 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;
    }
};

你可能感兴趣的:(leetcode,c++,算法,开发语言)