搜索——A*

struct AStar{
    // 计算预估代价
    static int getH(const string& status, const string& target){
        int ret = 0;
        for(int i=0;i < 4;i++){
            int dist = abs(int(status[i]) - int(target[i]));
            ret+= min(dist,10-dist);
        }
        return ret;
    }
    // 构造函数
    AStar(const string& status, const string& target, int g): status_{status},g_{g},h_{getH(status,target)} {
        f_ = h_+g_;
    } 
    // 重载 < 升序 
    bool operator < (const AStar& that) const{
        return f_>that.f_;
    }
    string status_;
    int g_; // 从起点(初始状态)开始的距离函数  当前代价
    int h_; // 到终点(最终状态)的距离函数  预估代价
    int f_; // 以及每个点的估价函数 总代价
};
class Solution {
public:
    int openLock(vector<string>& deadends, string target) {
        if(target == "0000"){
            return 0;
        }
        unordered_set<string> dead(deadends.begin(),deadends.end());
        if(dead.count("0000")>0 || dead.count(target)>0){
            return -1;
        }
        
        auto num_prev = [](char x)->char{
            return (x == '0'? '9':x-1);
        };
        auto num_subv = [](char x)-> char{
            return (x == '9'? '0':x+1); 
        };
        auto get = [&](string& status)->vector<string>{
            vector<string> ret;
            for(int i=0;i<4;i++){
                char te = status[i];
                status[i] = num_prev(te);
                ret.push_back(status);
                status[i] = num_subv(te);                
                ret.push_back(status);
                status[i] = te;
            }
            return ret;
        };
        unordered_set<string> see ={"0000"};
        
        priority_queue<AStar> q;
        q.emplace("0000",target,0);

        while(!q.empty()){
            AStar top = q.top();
            q.pop();
            for(auto&& s: get(top.status_)){
                if(dead.count(s)>0 || see.count(s)>0){
                    continue;
                }
                if(s == target){
                    return top.g_+1;
                }
                q.emplace(s,target,top.g_+1);
                see.emplace(move(s));

            }
        }
        return -1;
    }
};

跳转
跳转

题目

跳转

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值