POJ2243 A*算法BFS

A*算法是一种有预判优化的搜索根据两个参数g和h和优先队列,选择比较好的下一步。

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <queue>
using namespace std;

struct node{
    int x,y,step,g,h,f;
    bool operator < (const node & k) const{
        return f > k.f;
    }
};
bool v[11][11];
int mx[] = {1,1,-1,-1,2,2,-2,-2};
int my[] = {2,-2,2,-2,1,-1,1,-1};
bool in(int x,int y){
    if(x >= 1 && x <= 8 && y >= 1 && y <= 8)
        return true;
    else
        return false;
}
int hdis(node a,node b){
    return (abs(a.x - b.x) + abs(a.y - b.y))*10;
}

priority_queue<node> q;
int Astar(node s,node e){
    while(!q.empty())
        q.pop();
    memset(v,0,sizeof(v));
    v[s.x][s.y] = 1;
    s.step = 0;
    s.f = s.g = 0;
    s.h = hdis(s,e);
    q.push(s);
    while(!q.empty()){
        node temp = q.top();
        q.pop();
        if(temp.x == e.x && temp.y == e.y){
            return temp.step;
        }
        for(int i = 0 ; i < 8 ; i ++){
            node nt = temp;
            nt.x += mx[i];
            nt.y += my[i];
            if(in(nt.x,nt.y) && v[nt.x][nt.y] == 0){
                v[nt.x][nt.y] = 1;
                nt.step++;
                nt.g += 23;
                nt.h = hdis(nt,e);
                nt.f = nt.g + nt.h;
                q.push(nt);
            }

        }
    }
}
char s[3];
char e[3];
int main(){
    while(scanf("%s%s",&s,&e) != EOF){
        node src,des;
        src.x = int(s[0] - 'a' + 1);
        src.y = int(s[1] - '0');
        des.x = int(e[0] - 'a' + 1);
        des.y = int(e[1] - '0');
        printf("To get from %s to %s takes %d knight moves.\n",s,e,Astar(src,des));
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值